Xarray in 45 minutes#


Adapted (actually copied) from https://tutorial.xarray.dev/overview/xarray-in-45-min

Twitter: @nilodna GitHub: nilodna


In this lesson, we discuss cover the basics of Xarray data structures. By the end of the lesson, we will be able to:

  • Understand the basic data structures in Xarray

  • Inspect DataArray and Dataset objects.

  • Read and write netCDF files using Xarray.

  • Understand that there are many packages that build on top of xarray

We’ll start by reviewing the various components of the Xarray data model, represented here visually:

import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

%matplotlib inline
%config InlineBackend.figure_format='retina'

Xarray has a few small real-world tutorial datasets hosted in the xarray-data GitHub repository.

xarray.tutorial.load_dataset is a convenience function to download and open DataSets by name (listed at that link).

Here we’ll use air temperature from the National Center for Environmental Prediction. Xarray objects have convenient HTML representations to give an overview of what we’re working with:

ds = xr.tutorial.load_dataset("air_temperature")
ds

Note that behind the scenes the tutorial.open_dataset downloads a file. It then uses xarray.open_dataset function to open that file (which for this datasets is a netCDF file).

A few things are done automatically upon opening, but controlled by keyword arguments. For example, try passing the keyword argument mask_and_scale=False… what happens?

What’s in a Dataset?#

Many DataArrays!

What’s a DataArray?

Datasets are dictionary-like containers of DataArrays. They are a mapping of variable name to DataArray:

# pull out "air" dataarray with dictionary syntax
ds["air"]

You can save some typing by using the “attribute” or “dot” notation. This won’t work for variable names that clash with a built-in method name (like mean for example).

# pull out dataarray using dot notation
ds.air

What’s in a DataArray?#

data + (a lot of) metadata

Named dimensions#

.dims correspond to the axes of your data.

In this case we have 2 spatial dimensions (latitude and longitude are store with shorthand names lat and lon) and one temporal dimension (time).

ds.air.dims

Coordinate variables#

.coords is a simple data container for coordinate variables.

Here we see the actual timestamps and spatial positions of our air temperature data:

ds.air.coords

Coordinates objects support similar indexing notation

# extracting coordinate variables
ds.air.lon
# extracting coordinate variables from .coords
ds.coords["lon"]

It is useful to think of the values in these coordinate variables as axis “labels” such as “tick labels” in a figure. These are coordinate locations on a grid at which you have data.

Arbitrary attributes#

.attrs is a dictionary that can contain arbitrary Python objects (strings, lists, integers, dictionaries, etc.) Your only limitation is that some attributes may not be writeable to certain file formats.

ds.air.attrs
# assign your own attributes!
ds.air.attrs["who_is_awesome"] = "xarray"
ds.air.attrs
ds.air

Underlying data#

.data contains the numpy array storing air temperature values.

Xarray structures wrap underlying simpler array-like data structures. This part of Xarray is quite extensible allowing for distributed array, GPU arrays, sparse arrays, arrays with units etc. We’ll briefly look at this later in this tutorial.

ds.air.data
# what is the type of the underlying data
type(ds.air.data)

Review#

Xarray provides two main data structures:

  1. DataArrays that wrap underlying data containers (e.g. numpy arrays) and contain associated metadata

  2. DataSets that are dictionary-like containers of DataArrays


Why Xarray?#

Metadata provides context and provides code that is more legible. This reduces the likelihood of errors from typos and makes analysis more intuitive and fun!

Analysis without xarray: 😖#

# plot the first timestep
lat = ds.air.lat.data  # numpy array
lon = ds.air.lon.data  # numpy array
temp = ds.air.data  # numpy array
plt.figure()
plt.pcolormesh(lon, lat, temp[0, :, :]);
temp.mean(axis=1)  ## what did I just do? I can't tell by looking at this line.

Analysis with xarray 😎#

How readable is this code?

ds.air.isel(time=0).plot(x="lon");

Use dimension names instead of axis numbers

ds.air.mean(dim="time").plot(x="lon")

Extracting data or “indexing”#

Xarray supports

  • label-based indexing using .sel

  • position-based indexing using .isel

See the user guide for more.

Label-based indexing#

Xarray inherits its label-based indexing rules from pandas; this means great support for dates and times!

# here's what ds looks like
ds
# pull out data for all of 2013-May
ds.sel(time="2013-05")
# demonstrate slicing
ds.sel(time=slice("2013-05", "2013-07"))
ds.sel(time="2013")
# demonstrate "nearest" indexing
ds.sel(lon=240.2, method="nearest")
# "nearest indexing at multiple points"
ds.sel(lon=[240.125, 234], lat=[40.3, 50.3], method="nearest")

Position-based indexing#

This is similar to your usual numpy array[0, 2, 3] but with the power of named dimensions!

ds.air.data[0, 2, 3]
# pull out time index 0, lat index 2, and lon index 3
ds.air.isel(time=0, lat=2, lon=3)  #  much better than ds.air[0, 2, 3]
# demonstrate slicing
ds.air.isel(lat=slice(10))

Concepts for computation#

Consider calculating the mean air temperature per unit surface area for this dataset. Because latitude and longitude correspond to spherical coordinates for Earth’s surface, each 2.5x2.5 degree grid cell actually has a different surface area as you move away from the equator! This is because latitudinal length is fixed ($ \delta Lat = R \delta \phi $), but longitudinal length varies with latitude ($ \delta Lon = R \delta \lambda \cos(\phi) $)

So the area element for lat-lon coordinates is

$$ \delta A = R^2 \delta\phi , \delta\lambda \cos(\phi) $$

where $\phi$ is latitude, $\delta \phi$ is the spacing of the points in latitude, $\delta \lambda$ is the spacing of the points in longitude, and $R$ is Earth’s radius. (In this formula, $\phi$ and $\lambda$ are measured in radians)

# Earth's average radius in meters
R = 6.371e6

# Coordinate spacing for this dataset is 2.5 x 2.5 degrees
 = np.deg2rad(2.5)
 = np.deg2rad(2.5)

dlat = R *  * xr.ones_like(ds.air.lon)
dlon = R *  * np.cos(np.deg2rad(ds.air.lat))

There are two concepts here:

  1. you can call functions like np.cos and np.deg2rad (“numpy ufuncs”) on Xarray objects and receive an Xarray object back.

  2. We used ones_like to create a DataArray that looks like ds.air.lon in all respects, except that the data are all ones

# returns an xarray DataArray!
np.cos(np.deg2rad(ds.lat))
# cell latitude length is constant with longitude
dlat
# cell longitude length changes with latitude
dlon

Broadcasting: expanding data#

Our longitude and latitude length DataArrays are both 1D with different dimension names. If we multiple these DataArrays together the dimensionality is expanded to 2D by broadcasting:

cell_area = dlon * dlat
cell_area

The result has two dimensions because xarray realizes that dimensions lon and lat are different so it automatically “broadcasts” to get a 2D result. See the last row in this image from Jake VanderPlas Python Data Science Handbook

Because xarray knows about dimension names we avoid having to create unnecessary size-1 dimensions using np.newaxis or .reshape. For more, see the user guide


Alignment: putting data on the same grid#

When doing arithmetic operations xarray automatically “aligns” i.e. puts the data on the same grid. In this case cell_area and ds.air are at the same lat, lon points we end up with a result with the same shape (25x53):

ds.air.isel(time=1) / cell_area

Now lets make cell_area unaligned i.e. change the coordinate labels

# make a copy of cell_area
# then add 1e-5 degrees to latitude
cell_area_bad = cell_area.copy(deep=True)
cell_area_bad["lat"] = cell_area.lat + 1e-5  # latitudes are off by 1e-5 degrees!
cell_area_bad
cell_area_bad * ds.air.isel(time=1)

The result is an empty array with no latitude coordinates because none of them were aligned!

Tip: If you notice extra NaNs or missing points after xarray computation, it means that your xarray coordinates were not aligned exactly.

For more, see the Xarray documentation. This tutorial notebook also covers alignment and broadcasting (highly recommended)

To make sure variables are aligned as you think they are, do the following:

xr.align(cell_area_bad, ds.air, join="exact")

The above statement raises an error since the two are not aligned.


High level computation#

(groupby, resample, rolling, coarsen, weighted)

Xarray has some very useful high level objects that let you do common computations:

  1. groupby : Bin data in to groups and reduce

  2. resample : Groupby specialized for time axes. Either downsample or upsample your data.

  3. rolling : Operate on rolling windows of your data e.g. running mean

  4. coarsen : Downsample your data

  5. weighted : Weight your data before reducing

Below we quickly demonstrate these patterns. See the user guide links above and the tutorial for more.

groupby#

# here's ds
ds
# seasonal groups
ds.groupby("time.season")
# make a seasonal mean
seasonal_mean = ds.groupby("time.season").mean()
seasonal_mean

The seasons are out of order (they are alphabetically sorted). This is a common annoyance. The solution is to use .sel to change the order of labels

seasonal_mean = seasonal_mean.sel(season=["DJF", "MAM", "JJA", "SON"])
seasonal_mean
seasonal_mean.air.plot(col="season")

resample#

# resample to monthly frequency
ds.resample(time="M").mean()

weighted#

# weight by cell_area and take mean over (time, lon)
ds.weighted(cell_area).mean(["lon", "time"]).air.plot(y="lat");

Visualization#

(.plot)

We have seen very simple plots earlier. Xarray also lets you easily visualize 3D and 4D datasets by presenting multiple facets (or panels or subplots) showing variations across rows and/or columns.

# facet the seasonal_mean
seasonal_mean.air.plot(col="season", col_wrap=2);
# contours
seasonal_mean.air.plot.contour(col="season", levels=20, add_colorbar=True);
# line plots too? wut
seasonal_mean.air.mean("lon").plot.line(hue="season", y="lat");

For more see the user guide, the gallery, and the tutorial material.


Reading and writing files#

Xarray supports many disk formats. Below is a small example using netCDF. For more see the documentation

# write to netCDF
ds.to_netcdf("my-example-dataset.nc")

Note

To avoid the SerializationWarning you can assign a _FillValue for any NaNs in ‘air’ array by adding the keyword argument encoding=dict(air={_FillValue=-9999})

# read from disk
fromdisk = xr.open_dataset("my-example-dataset.nc")
fromdisk
# check that the two are identical
ds.identical(fromdisk)

Tip: A common use case to read datasets that are a collection of many netCDF files. See the documentation for how to handle that.

Finally to read other file formats, you might find yourself reading in the data using a different library and then creating a DataArray(docs, tutorial) from scratch. For example, you might use h5py to open an HDF5 file and then create a Dataset from that. For MATLAB files you might use scipy.io.loadmat or h5py depending on the version of MATLAB file you’re opening and then construct a Dataset.


The scientific python ecosystem#

Xarray ties in to the larger scientific python ecosystem and in turn many packages build on top of xarray. A long list of such packages is here: https://docs.xarray.dev/en/stable/related-projects.html.

Now we will demonstrate some cool features.

Pandas: tabular data structures#

You can easily convert between xarray and pandas structures. This allows you to conveniently use the extensive pandas ecosystem of packages (like seaborn) for your work.

# convert to pandas dataframe
df = ds.isel(time=slice(10)).to_dataframe()
df
# convert dataframe to xarray
df.to_xarray()

Alternative array types#

This notebook has focused on Numpy arrays. Xarray can wrap other array types! For example:

distributed parallel arrays & Xarray user guide on Dask

pydata/sparse : sparse arrays

GPU arrays & cupy-xarray

pint : unit-aware arrays & pint-xarray

Dask#

Dask cuts up NumPy arrays into blocks and parallelizes your analysis code across these blocks

# demonstrate dask dataset
dasky = xr.tutorial.open_dataset(
    "air_temperature",
    chunks={"time": 10},  # 10 time steps in each block
)

dasky.air

All computations with dask-backed xarray objects are lazy, allowing you to build up a complicated chain of analysis steps quickly

# demonstrate lazy mean
dasky.air.mean("lat")

To get concrete values, call .compute or .load

# "compute" the mean
dasky.air.mean("lat").compute()

HoloViz#

Quickly generate interactive plots from your data!

The hvplot package attaches itself to all xarray objects under the .hvplot namespace. So instead of using .plot use .hvplot

import hvplot.xarray

ds.air.hvplot(groupby="time", clim=(270, 300), widget_location='bottom')

Note

The time slider will only work if you’re executing the notebook, rather than viewing the website

cf_xarray#

cf_xarray is a project that tries to let you make use of other CF attributes that xarray ignores. It attaches itself to all xarray objects under the .cf namespace.

Where xarray allows you to specify dimension names for analysis, cf_xarray lets you specify logical names like "latitude" or "longitude" instead as long as the appropriate CF attributes are set.

For example, the "longitude" dimension in different files might be labelled as: (lon, LON, long, x…), but cf_xarray let’s you always refer to the logical name "longitude" in your code:

import cf_xarray
# describe cf attributes in dataset
ds.air.cf

The following mean operation will work with any dataset that has appropriate attributes set that allow detection of the “latitude” variable (e.g. units: "degress_north" or standard_name: "latitude")

# demonstrate equivalent of .mean("lat")
ds.air.cf.mean("latitude")
# demonstrate indexing
ds.air.cf.sel(longitude=242.5, method="nearest")

Other cool packages#

  • xgcm : grid-aware operations with xarray objects

  • xrft : fourier transforms with xarray

  • xclim : calculating climate indices with xarray objects

  • intake-xarray : forget about file paths

  • rioxarray : raster files and xarray

  • xesmf : regrid using ESMF

  • MetPy : tools for working with weather data

Check the Xarray Ecosystem page and this tutorial for even more packages and demonstrations.

Next#

  1. Read the tutorial material and user guide

  2. See the description of common terms used in the xarray documentation:

  3. Answers to common questions on “how to do X” with Xarray are here

  4. Ryan Abernathey has a book on data analysis with a chapter on Xarray

  5. Project Pythia has foundational and more advanced material on Xarray. Pythia also aggregates other Python learning resources.

  6. The Xarray Github Discussions and Pangeo Discourse are good places to ask questions.

  7. Tell your friends! Tweet!

Welcome!#

Xarray is an open-source project and gladly welcomes all kinds of contributions. This could include reporting bugs, discussing new enhancements, contributing code, helping answer user questions, contributing documentation (even small edits like fixing spelling mistakes or rewording to make the text clearer). Welcome!