Quick overview

Here are some quick examples of what you can do with xarray.DataArrayobjects. Everything is explained in much more detail in the rest of thedocumentation.

To begin, import numpy, pandas and xarray using their customary abbreviations:

  1. In [1]: import numpy as np
  2.  
  3. In [2]: import pandas as pd
  4.  
  5. In [3]: import xarray as xr

Create a DataArray

You can make a DataArray from scratch by supplying data in the form of a numpyarray or list, with optional dimensions and coordinates:

  1. In [4]: data = xr.DataArray(np.random.randn(2, 3),
  2. ...: dims=('x', 'y'),
  3. ...: coords={'x': [10, 20]})
  4. ...:
  5.  
  6. In [5]: data
  7. Out[5]:
  8. <xarray.DataArray (x: 2, y: 3)>
  9. array([[-1.039575, 0.27186 , -0.424972],
  10. [ 0.56702 , 0.276232, -1.087401]])
  11. Coordinates:
  12. * x (x) int64 10 20
  13. Dimensions without coordinates: y

In this case, we have generated a 2D array, assigned the names x and y to the two dimensions respectively and associated two coordinate labels ‘10’ and ‘20’ with the two locations along the x dimension. If you supply a pandas Series or DataFrame, metadata is copied directly:

  1. In [6]: xr.DataArray(pd.Series(range(3), index=list('abc'), name='foo'))
  2. Out[6]:
  3. <xarray.DataArray 'foo' (dim_0: 3)>
  4. array([0, 1, 2])
  5. Coordinates:
  6. * dim_0 (dim_0) object 'a' 'b' 'c'

Here are the key properties for a DataArray:

  1. # like in pandas, values is a numpy array that you can modify in-place
  2. In [7]: data.values
  3. Out[7]:
  4. array([[-1.04 , 0.272, -0.425],
  5. [ 0.567, 0.276, -1.087]])
  6.  
  7. In [8]: data.dims
  8. Out[8]: ('x', 'y')
  9.  
  10. In [9]: data.coords
  11. Out[9]:
  12. Coordinates:
  13. * x (x) int64 10 20
  14.  
  15. # you can use this dictionary to store arbitrary metadata
  16. In [10]: data.attrs
  17. Out[10]: OrderedDict()

Indexing

xarray supports four kind of indexing. Since we have assigned coordinate labels to the x dimension we can use label-based indexing along that dimension just like pandas. The four examples below all yield the same result but at varying levels of convenience and intuitiveness.

  1. # positional and by integer label, like numpy
  2. In [11]: data[[0, 1]]
  3. Out[11]:
  4. <xarray.DataArray (x: 2, y: 3)>
  5. array([[-1.039575, 0.27186 , -0.424972],
  6. [ 0.56702 , 0.276232, -1.087401]])
  7. Coordinates:
  8. * x (x) int64 10 20
  9. Dimensions without coordinates: y
  10.  
  11. # positional and by coordinate label, like pandas
  12. In [12]: data.loc[10:20]
  13. Out[12]:
  14. <xarray.DataArray (x: 2, y: 3)>
  15. array([[-1.039575, 0.27186 , -0.424972],
  16. [ 0.56702 , 0.276232, -1.087401]])
  17. Coordinates:
  18. * x (x) int64 10 20
  19. Dimensions without coordinates: y
  20.  
  21. # by dimension name and integer label
  22. In [13]: data.isel(x=slice(2))
  23. Out[13]:
  24. <xarray.DataArray (x: 2, y: 3)>
  25. array([[-1.039575, 0.27186 , -0.424972],
  26. [ 0.56702 , 0.276232, -1.087401]])
  27. Coordinates:
  28. * x (x) int64 10 20
  29. Dimensions without coordinates: y
  30.  
  31. # by dimension name and coordinate label
  32. In [14]: data.sel(x=[10, 20])
  33. Out[14]:
  34. <xarray.DataArray (x: 2, y: 3)>
  35. array([[-1.039575, 0.27186 , -0.424972],
  36. [ 0.56702 , 0.276232, -1.087401]])
  37. Coordinates:
  38. * x (x) int64 10 20
  39. Dimensions without coordinates: y

Unlike positional indexing, label-based indexing frees us from having to know how our array is organized. All we need to know are the dimension name and the label we wish to index i.e. data.sel(x=10) works regardless of whether x is the first or second dimension of the array and regardless of whether 10 is the first or second element of x. We have already told xarray that x is the first dimension when we created data: xarray keeps track of this so we don’t have to. For more, see Indexing and selecting data.

Attributes

While you’re setting up your DataArray, it’s often a good idea to set metadata attributes. A useful choice is to set data.attrs['long_name'] and data.attrs['units'] since xarray will use these, if present, to automatically label your plots. These special names were chosen following the NetCDF Climate and Forecast (CF) Metadata Conventions. attrs is just a Python dictionary, so you can assign anything you wish.

  1. In [15]: data.attrs['long_name'] = 'random velocity'
  2.  
  3. In [16]: data.attrs['units'] = 'metres/sec'
  4.  
  5. In [17]: data.attrs['description'] = 'A random variable created as an example.'
  6.  
  7. In [18]: data.attrs['random_attribute'] = 123
  8.  
  9. In [19]: data.attrs
  10. Out[19]:
  11. OrderedDict([('long_name', 'random velocity'),
  12. ('units', 'metres/sec'),
  13. ('description', 'A random variable created as an example.'),
  14. ('random_attribute', 123)])
  15.  
  16. # you can add metadata to coordinates too
  17. In [20]: data.x.attrs['units'] = 'x units'

Computation

Data arrays work very similarly to numpy ndarrays:

  1. In [21]: data + 10
  2. Out[21]:
  3. <xarray.DataArray (x: 2, y: 3)>
  4. array([[ 8.960425, 10.27186 , 9.575028],
  5. [10.56702 , 10.276232, 8.912599]])
  6. Coordinates:
  7. * x (x) int64 10 20
  8. Dimensions without coordinates: y
  9.  
  10. In [22]: np.sin(data)
  11. Out[22]:
  12. <xarray.DataArray (x: 2, y: 3)>
  13. array([[-0.862189, 0.268523, -0.412296],
  14. [ 0.537121, 0.272732, -0.885422]])
  15. Coordinates:
  16. * x (x) int64 10 20
  17. Dimensions without coordinates: y
  18.  
  19. # transpose
  20. In [23]: data.T
  21. Out[23]:
  22. <xarray.DataArray (y: 3, x: 2)>
  23. array([[-1.039575, 0.56702 ],
  24. [ 0.27186 , 0.276232],
  25. [-0.424972, -1.087401]])
  26. Coordinates:
  27. * x (x) int64 10 20
  28. Dimensions without coordinates: y
  29. Attributes:
  30. long_name: random velocity
  31. units: metres/sec
  32. description: A random variable created as an example.
  33. random_attribute: 123
  34.  
  35. In [24]: data.sum()
  36. Out[24]:
  37. <xarray.DataArray ()>
  38. array(-1.436836)

However, aggregation operations can use dimension names instead of axisnumbers:

  1. In [25]: data.mean(dim='x')
  2. Out[25]:
  3. <xarray.DataArray (y: 3)>
  4. array([-0.236277, 0.274046, -0.756187])
  5. Dimensions without coordinates: y

Arithmetic operations broadcast based on dimension name. This means you don’tneed to insert dummy dimensions for alignment:

  1. In [26]: a = xr.DataArray(np.random.randn(3), [data.coords['y']])
  2.  
  3. In [27]: b = xr.DataArray(np.random.randn(4), dims='z')
  4.  
  5. In [28]: a
  6. Out[28]:
  7. <xarray.DataArray (y: 3)>
  8. array([-0.67369 , 0.113648, -1.478427])
  9. Coordinates:
  10. * y (y) int64 0 1 2
  11.  
  12. In [29]: b
  13. Out[29]:
  14. <xarray.DataArray (z: 4)>
  15. array([ 0.524988, 0.404705, 0.577046, -1.715002])
  16. Dimensions without coordinates: z
  17.  
  18. In [30]: a + b
  19. Out[30]:
  20. <xarray.DataArray (y: 3, z: 4)>
  21. array([[-0.148702, -0.268984, -0.096644, -2.388692],
  22. [ 0.638636, 0.518354, 0.690694, -1.601354],
  23. [-0.953439, -1.073721, -0.901381, -3.193429]])
  24. Coordinates:
  25. * y (y) int64 0 1 2
  26. Dimensions without coordinates: z

It also means that in most cases you do not need to worry about the order ofdimensions:

  1. In [31]: data - data.T
  2. Out[31]:
  3. <xarray.DataArray (x: 2, y: 3)>
  4. array([[0., 0., 0.],
  5. [0., 0., 0.]])
  6. Coordinates:
  7. * x (x) int64 10 20
  8. Dimensions without coordinates: y

Operations also align based on index labels:

  1. In [32]: data[:-1] - data[:1]
  2. Out[32]:
  3. <xarray.DataArray (x: 1, y: 3)>
  4. array([[0., 0., 0.]])
  5. Coordinates:
  6. * x (x) int64 10
  7. Dimensions without coordinates: y

For more, see Computation.

GroupBy

xarray supports grouped operations using a very similar API to pandas (see GroupBy: split-apply-combine):

  1. In [33]: labels = xr.DataArray(['E', 'F', 'E'], [data.coords['y']], name='labels')
  2.  
  3. In [34]: labels
  4. Out[34]:
  5. <xarray.DataArray 'labels' (y: 3)>
  6. array(['E', 'F', 'E'], dtype='<U1')
  7. Coordinates:
  8. * y (y) int64 0 1 2
  9.  
  10. In [35]: data.groupby(labels).mean('y')
  11. Out[35]:
  12. <xarray.DataArray (x: 2, labels: 2)>
  13. array([[-0.732274, 0.27186 ],
  14. [-0.26019 , 0.276232]])
  15. Coordinates:
  16. * x (x) int64 10 20
  17. * labels (labels) object 'E' 'F'
  18.  
  19. In [36]: data.groupby(labels).apply(lambda x: x - x.min())
  20. Out[36]:
  21. <xarray.DataArray (x: 2, y: 3)>
  22. array([[0.047826, 0. , 0.662428],
  23. [1.654421, 0.004372, 0. ]])
  24. Coordinates:
  25. * x (x) int64 10 20
  26. * y (y) int64 0 1 2
  27. labels (y) <U1 'E' 'F' 'E'

Plotting

Visualizing your datasets is quick and convenient:

  1. In [37]: data.plot()
  2. Out[37]: <matplotlib.collections.QuadMesh at 0x7f33f267b710>

_images/plotting_quick_overview.pngNote the automatic labeling with names and units. Our effort in adding metadata attributes has paid off! Many aspects of these figures are customizable: see Plotting.

pandas

Xarray objects can be easily converted to and from pandas objects using the to_series(), to_dataframe() and to_xarray() methods:

  1. In [38]: series = data.to_series()
  2.  
  3. In [39]: series
  4. Out[39]:
  5. x y
  6. 10 0 -1.039575
  7. 1 0.271860
  8. 2 -0.424972
  9. 20 0 0.567020
  10. 1 0.276232
  11. 2 -1.087401
  12. dtype: float64
  13.  
  14. # convert back
  15. In [40]: series.to_xarray()
  16. Out[40]:
  17. <xarray.DataArray (x: 2, y: 3)>
  18. array([[-1.039575, 0.27186 , -0.424972],
  19. [ 0.56702 , 0.276232, -1.087401]])
  20. Coordinates:
  21. * x (x) int64 10 20
  22. * y (y) int64 0 1 2

Datasets

xarray.Dataset is a dict-like container of aligned DataArrayobjects. You can think of it as a multi-dimensional generalization of thepandas.DataFrame:

  1. In [41]: ds = xr.Dataset({'foo': data, 'bar': ('x', [1, 2]), 'baz': np.pi})
  2.  
  3. In [42]: ds
  4. Out[42]:
  5. <xarray.Dataset>
  6. Dimensions: (x: 2, y: 3)
  7. Coordinates:
  8. * x (x) int64 10 20
  9. Dimensions without coordinates: y
  10. Data variables:
  11. foo (x, y) float64 -1.04 0.2719 -0.425 0.567 0.2762 -1.087
  12. bar (x) int64 1 2
  13. baz float64 3.142

This creates a dataset with three DataArrays named foo, bar and baz. Use dictionary or dot indexing to pull out Dataset variables as DataArray objects but note that assignment only works with dictionary indexing:

  1. In [43]: ds['foo']
  2. Out[43]:
  3. <xarray.DataArray 'foo' (x: 2, y: 3)>
  4. array([[-1.039575, 0.27186 , -0.424972],
  5. [ 0.56702 , 0.276232, -1.087401]])
  6. Coordinates:
  7. * x (x) int64 10 20
  8. Dimensions without coordinates: y
  9. Attributes:
  10. long_name: random velocity
  11. units: metres/sec
  12. description: A random variable created as an example.
  13. random_attribute: 123
  14.  
  15. In [44]: ds.foo
  16. Out[44]:
  17. <xarray.DataArray 'foo' (x: 2, y: 3)>
  18. array([[-1.039575, 0.27186 , -0.424972],
  19. [ 0.56702 , 0.276232, -1.087401]])
  20. Coordinates:
  21. * x (x) int64 10 20
  22. Dimensions without coordinates: y
  23. Attributes:
  24. long_name: random velocity
  25. units: metres/sec
  26. description: A random variable created as an example.
  27. random_attribute: 123

When creating ds, we specified that foo is identical to data created earlier, bar is one-dimensional with single dimension x and associated values ‘1’ and ‘2’, and baz is a scalar not associated with any dimension in ds. Variables in datasets can have different dtype and even different dimensions, but all dimensions are assumed to refer to points in the same shared coordinate system i.e. if two variables have dimension x, that dimension must be identical in both variables.

For example, when creating ds xarray automatically aligns bar with DataArray foo, i.e., they share the same coordinate system so that ds.bar['x'] == ds.foo['x'] == ds['x']. Consequently, the following works without explicitly specifying the coordinate x when creating ds['bar']:

  1. In [45]: ds.bar.sel(x=10)
  2. Out[45]:
  3. <xarray.DataArray 'bar' ()>
  4. array(1)
  5. Coordinates:
  6. x int64 10

You can do almost everything you can do with DataArray objects withDataset objects (including indexing and arithmetic) if you prefer to workwith multiple variables at once.

Read & write netCDF files

NetCDF is the recommended file format for xarray objects. Usersfrom the geosciences will recognize that the Dataset datamodel looks very similar to a netCDF file (which, in fact, inspired it).

You can directly read and write xarray objects to disk using to_netcdf(), open_dataset() andopen_dataarray():

  1. In [46]: ds.to_netcdf('example.nc')
  2.  
  3. In [47]: xr.open_dataset('example.nc')
  4. Out[47]:
  5. <xarray.Dataset>
  6. Dimensions: (x: 2, y: 3)
  7. Coordinates:
  8. * x (x) int64 10 20
  9. Dimensions without coordinates: y
  10. Data variables:
  11. foo (x, y) float64 ...
  12. bar (x) int64 ...
  13. baz float64 ...

It is common for datasets to be distributed across multiple files (commonly one file per timestep). xarray supports this use-case by providing the open_mfdataset() and the save_mfdataset() methods. For more, see Reading and writing files.