Xarray for multidimensional gridded data¶
In last week's lecture, we saw how Pandas provided a way to keep track of additional "metadata" surrounding tabular datasets, including "indexes" for each row and labels for each column. These features, together with Pandas' many useful routines for all kinds of data munging and analysis, have made Pandas one of the most popular python packages in the world.
However, not all Earth science datasets easily fit into the "tabular" model (i.e. rows and columns) imposed by Pandas. In particular, we often deal with multidimensional data. By multidimensional data (also often called N-dimensional), I mean data with many independent dimensions or axes. For example, we might represent Earth's surface temperature $T$ as a three dimensional variable
$$ T(x, y, t) $$where $x$ is longitude, $y$ is latitude, and $t$ is time.
The point of xarray is to provide pandas-level convenience for working with this type of data.
Learning Goals for Xarray¶
Because of the importance of xarray for data analysis in geoscience, we are going to spend a long time on it. The goals of the next three lessons include the following.
Lesson 1: Xarray Fundamentals¶
Dataset Creation¶
- Describe the core xarray data structures, the
DataArray
and theDataset
, and the components that make them up, including: Data Variables, Dimensions, Coordinates, Indexes, and Attributes - Create xarray
DataArrays
andDataSets
out of raw numpy arrays - Create xarray objects with and without indexes
- Load xarray datasets from netCDF files and openDAP servers
- View and set attributes
Basic Indexing and Interpolation¶
- Select data by position using
.isel
with values or slices - Select data by label using
.sel
with values or slices - Select timeseries data by date/time with values or slices
- Use nearest-neighbor lookups with
.sel
- Mask data with
.where
- Interpolate data in one and several dimensions
Basic Computation¶
- Do basic arithmetic with DataArrays and Datasets
- Use numpy universal function on DataArrays and Datasets, or use corresponding built-in xarray methods
- Combine multiple xarray objects in arithmetic operations and understand how they are broadcasted / aligned
- Perform aggregation (reduction) along one or multiple dimensions of a DataArray or Dataset
Basic Plotting¶
- Use built-in xarray plotting for 1D and 2D DataArrays
- Customize plots with options
Lesson 2: Advanced Usage¶
Xarray's groupby, resample, and rolling¶
- Split xarray objects into groups using
groupby
- Apply reduction operations to groups (e.g. mean)
- Apply non-reducing functions to groups (e.g. standardize)
- Use
groupby
with time coordinates (e.g. to create climatologies) - Use artimetic between
GroupBy
objects and regular DataArrays / Datasets - Use
groupby_bins
to aggregate data in bins - Use
resample
on time dimensions - Use
rolling
to apply rolling aggregations
Merging Combining Datasets¶
- Concatentate DataArrays and Datasets along a new or existing dimension
- Merge multiple datasets with different variables
- Add a new data variable to an existing Dataset
Reshaping Data¶
- Transpose dimension order
- Swap coordinates
- Expand and squeeze dimensions
- Convert between DataArray and Dataset
- Use
stack
andunstack
to transform data
Advanced Computations¶
- Use
differentiate
to take derivatives of data - Use
apply_ufunc
to apply custom or specialized operations to data
Plotting¶
- Show multiple line plots over a dimension using the
hue
keyword - Create multiple 2D plots using faceting
Lesson 1: Xarray Fundamentals¶
Xarray data structures¶
Like Pandas, xarray has two fundamental data structures:
- a
DataArray
, which holds a single multi-dimensional variable and its coordinates - a
Dataset
, which holds multiple variables that potentially share the same coordinates
DataArray¶
A DataArray
has four essential attributes:
values
: anumpy.ndarray
holding the array’s valuesdims
: dimension names for each axis (e.g.,('x', 'y', 'z')
)coords
: a dict-like container of arrays (coordinates) that label each point (e.g., 1-dimensional arrays of numbers, datetime objects or strings)attrs
: anOrderedDict
to hold arbitrary metadata (attributes)
Let's start by constructing some DataArrays manually
import numpy as np
import xarray as xr
from matplotlib import pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (8,5)
A simple DataArray without dimensions or coordinates isn't much use.
da = xr.DataArray([9, 0, 2, 1, 0])
da
We can add a dimension name...
da = xr.DataArray([9, 0, 2, 1, 0], dims=['x'])
da
But things get most interesting when we add a coordinate:
da = xr.DataArray([9, 0, 2, 1, 0],
dims=['x'],
coords={'x': [10, 20, 30, 40, 50]})
da
Xarray has built-in plotting, like pandas.
da.plot(marker='o')
Multidimensional DataArray¶
If we are just dealing with 1D data, Pandas and Xarray have very similar capabilities. Xarray's real potential comes with multidimensional data.
Let's go back to the multidimensional ARGO data we loaded in the numpy lesson. If you haven't already downloaded it, you can do so at the command line with
curl -O http://www.ldeo.columbia.edu/~rpa/argo_float_4901412.npz
We reload this data and examine its keys.
argo_data = np.load('argo_float_4901412.npz')
argo_data.keys()
The values of the argo_data
object are numpy arrays.
S = argo_data.f.S
T = argo_data.f.T
P = argo_data.f.P
levels = argo_data.f.levels
lon = argo_data.f.lon
lat = argo_data.f.lat
date = argo_data.f.date
print(S.shape, lon.shape, date.shape)
Let's organize the data and coordinates of the salinity variable into a DataArray.
da_salinity = xr.DataArray(S, dims=['level', 'date'],
coords={'level': levels,
'date': date},)
da_salinity
da_salinity.plot(yincrease=False)
Attributes can be used to store metadata. What metadata should you store? The CF Conventions are a great resource for thinking about climate metadata. Below we define two of the required CF-conventions attributes.
da_salinity.attrs['units'] = 'PSU'
da_salinity.attrs['standard_name'] = 'sea_water_salinity'
da_salinity
Datasets¶
A Dataset holds many DataArrays which potentially can share coordinates. In analogy to pandas:
pandas.Series : pandas.Dataframe :: xarray.DataArray : xarray.Dataset
Constructing Datasets manually is a bit more involved in terms of syntax. The Dataset constructor takes three arguments:
data_vars
should be a dictionary with each key as the name of the variable and each value as one of:- A
DataArray
or Variable - A tuple of the form
(dims, data[, attrs])
, which is converted into arguments for Variable - A pandas object, which is converted into a
DataArray
- A 1D array or list, which is interpreted as values for a one dimensional coordinate variable along the same dimension as it’s name
- A
coords
should be a dictionary of the same form as data_vars.attrs
should be a dictionary.
Let's put together a Dataset with temperature, salinity and pressure all together
argo = xr.Dataset(
data_vars={'salinity': (('level', 'date'), S),
'temperature': (('level', 'date'), T),
'pressure': (('level', 'date'), P)},
coords={'level': levels,
'date': date})
argo
What about lon and lat? We forgot them in the creation process, but we can add them after the fact.
argo.coords['lon'] = lon
argo
That was not quite right...we want lon to have dimension date
:
del argo['lon']
argo.coords['lon'] = ('date', lon)
argo.coords['lat'] = ('date', lat)
argo
Coordinates vs. Data Variables¶
Data variables can be modified through arithmentic operations or other functions. Coordinates are always keept the same.
argo * 10000
Clearly lon and lat are coordinates rather than data variables. We can change their status as follows:
argo = argo.set_coords(['lon', 'lat'])
argo
The *
symbol in the representation above indicates that level
and date
are "dimension coordinates" (they describe the coordinates associated with data variable axes) while lon
and lat
are "non-dimension coordinates". We can make any variable a non-dimension coordiante.
Alternatively, we could have assigned directly to coords as follows:
argo.coords['lon'] = ('date', lon)
argo.coords['lat'] = ('date', lat)
argo.salinity[2].plot()
argo.salinity[:, 10].plot()
However, it is often much more powerful to use xarray's .sel()
method to use label-based indexing.
argo.salinity.sel(level=2).plot()
argo.salinity.sel(date='2012-10-22').plot(y='level', yincrease=False)
.sel()
also supports slicing. Unfortunately we have to use a somewhat awkward syntax, but it still works.
argo.salinity.sel(date=slice('2012-10-01', '2012-12-01')).plot()
.sel()
also works on the whole Dataset
argo.sel(date='2012-10-22')
Computation¶
Xarray dataarrays and datasets work seamlessly with arithmetic operators and numpy array functions.
temp_kelvin = argo.temperature + 273.15
temp_kelvin.plot(yincrease=False)
We can also combine multiple xarray datasets in arithemtic operations
g = 9.8
buoyancy = g * (2e-4 * argo.temperature - 7e-4 * argo.salinity)
buoyancy.plot(yincrease=False)
Broadcasting¶
Broadcasting arrays in numpy is a nightmare. It is much easier when the data axes are labeled!
This is a useless calculation, but it illustrates how perfoming an operation on arrays with differenty coordinates will result in automatic broadcasting
level_times_lat = argo.level * argo.lat
level_times_lat
level_times_lat.plot()
Reductions¶
Just like in numpy, we can reduce xarray DataArrays along any number of axes:
argo.temperature.mean(axis=0).dims
argo.temperature.mean(axis=1).dims
However, rather than performing reductions on axes (as in numpy), we can perform them on dimensions. This turns out to be a huge convenience
argo_mean = argo.mean(dim='date')
argo_mean
argo_mean.salinity.plot(y='level', yincrease=False)
argo_std = argo.std(dim='date')
argo_std.salinity.plot(y='level', yincrease=False)
Loading Data from netCDF Files¶
NetCDF (Network Common Data Format) is the most widely used format for distributing geoscience data. NetCDF is maintained by the Unidata organization.
Below we quote from the NetCDF website:
NetCDF (network Common Data Form) is a set of interfaces for array-oriented data access and a freely distributed collection of data access libraries for C, Fortran, C++, Java, and other languages. The netCDF libraries support a machine-independent format for representing scientific data. Together, the interfaces, libraries, and format support the creation, access, and sharing of scientific data.
NetCDF data is:
- Self-Describing. A netCDF file includes information about the data it contains.
- Portable. A netCDF file can be accessed by computers with different ways of storing integers, characters, and floating-point numbers.
- Scalable. A small subset of a large dataset may be accessed efficiently.
- Appendable. Data may be appended to a properly structured netCDF file without copying the dataset or redefining its structure.
- Sharable. One writer and multiple readers may simultaneously access the same netCDF file.
- Archivable. Access to all earlier forms of netCDF data will be supported by current and future versions of the software.
Xarray was designed to make reading netCDF files in python as easy, powerful, and flexible as possible. (See xarray netCDF docs for more details.)
Below we download and load some the NASA GISSTemp global temperature anomaly dataset.
! wget https://data.giss.nasa.gov/pub/gistemp/gistemp1200_ERSSTv5.nc.gz
! gunzip gistemp1200_ERSSTv5.nc.gz
ds = xr.open_dataset('gistemp1200_ERSSTv5.nc')
ds
ds.tempanomaly.isel(time=-1).plot()
ds.tempanomaly.mean(dim=('lon', 'lat')).plot()