What is DataFrame.to_xarray() method in pandas?

The to_xarray method

The to_xarray method is used to convert the given DataFrame to a xarray object.

Note: Refer xarray to learn more about xarray data structure.

Note: Click here to learn more about the pandas library.

Syntax

DataFrame.to_xarray()

Parameters

The method has no parameters.

Code example

Let’s look at the code below:

import pandas as pd
df = pd.DataFrame({'Name':['Dom', 'Celeste', 'Abhi', 'Gaby', 'Rachel', 'Sam'],'Age': [20,25,30,18,25,20]})
xarr = df.to_xarray()
print("The xarray representation of the df is \n", xarr)

Code explanation

  • Line 3: We create a custom DataFrame called df.

  • Line 5: We invoke the to_xarray() on df to get the xarray representation of the DataFrame.