Pandas DataFrame to_xarray() Method


Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The Xarray library works with labeled multi-dimensional arrays and advanced analytics.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install xarray

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required library.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import xarray

DataFrame to_xarray()

The to_xarray() method returns an xarray. Dataset/xarray.DataArray from a DataFrame/Series dependent on the object passed.

πŸ’‘ Note: If the object is a DataFrame, the data converts to a Dataset.

If a Series, the data converts to a DataArray.

The syntax for this method is as follows:

DataFrame.to_xarray()

This method has no parameters.

For this example, Alice needs to grocery shop for a party. This DataFrame displays the grocery list (including categories, prices, and amounts). This object then converts to a Dataset.

Code – Example 1

df = pd.DataFrame([('Fruits',          'Apples',    3.97,   4),
                   ('Dairy',           'Milk',       2.43,   4),
                   ('Vegetables', 'Carrots',  4.21,  12),
                   ('Meat',           'Steak',    18.57, 4)],
                   columns=['Category', 'Name', 'Price', 'Quantity'])
print(df)

result = df.to_xarray()
print(result)
  • Line [1] creates a DataFrame from a list of tuples containing grocery list details and saves it to df.
  • Line [2] outputs the DataFrame to the terminal.
  • Line [3] converts the DataFrame to a Dataset. The output saves to result.
  • Line [4] outputs the result to the terminal.

Output

df

 CategoryNamePriceQuantity
0FruitsApples3.974
1DairyMilk2.434
2VegetablesCarrots4.2112
3MeatSteak18.574

result

Dimensions:   	(index: 4)
Coordinates:
  * index     	(index) int64 0 1 2 3
Data variables:
    Category	(index) object 'Fruits' 'Dairy' 'Vegetables' 'Meat'
    Name      	(index) object 'Apples' 'Milk' 'Carrots' 'Steak'
    Price     		(index) float64 3.97 2.43 4.21 18.57
    Quantity		(index) int64 4 4 12 4

You could also extract one (1) column from a DataFrame.

Code  – Example 2

df = pd.DataFrame([('Fruits', 'Apples', 3.97, 4),
                   ('Dairy', 'Milk', 2.43, 4),
                   ('Vegetables', 'Carrots', 4.21, 12),
                   ('Meat', 'Steak', 18.57, 4)],
                   columns=['Category', 'Name', 'Price', 'Quantity'])

result = df['Name'].to_xarray()
print(result)
  • Line [1] creates a DataFrame from a List of Tuples containing grocery list details and saves it to df.
  • Line [2] converts a column of the DataFrame to a Dataset. The output saves to result.
  • Line [3] outputs the result to the terminal.

Output

<xarray.DataArray 'Name' (index: 4)>
array(['Apples', 'Milk', 'Carrots', 'Steak'], dtype=object)
Coordinates:
  * index    (index) int64 0 1 2 3

This example converts a Series containing the first six (6) months of the year and the days per month to an xarray.

Code – Example 3

my_series = pd.Series(['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'June'])
my_idx    = [31, 28, 31, 30, 31, 30]
my_series.index = my_idx
print(my_series)

result = my_series.to_xarray()
print(result)
  • Line [1] creates a Series from a list of months.
  • Line [2] creates and sets the indexes as a list of days for each month.
  • Line [3] sets the index for the Series.
  • Line [4] outputs the Series to the terminal.
  • Line [5] converts the Series to an xarray.
  • Line [6] outputs the result to the terminal.

Output

my_series

31Jan.
28Feb.
31Mar.
30Apr.
31May
30June

result

dtype: object
<xarray.DataArray (index: 6)>
array(['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'June'], dtype=object)
Coordinates:
  * index    (index) int64 31 28 31 30 31 30

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.