Data Structures

DataArray

xarray.DataArray is xarray’s implementation of a labeled,multi-dimensional array. It has several key properties:

  • values: a numpy.ndarray holding the array’s values

  • dims: dimension names for each axis (e.g., ('x', 'y', 'z'))

  • coords: a dict-like container of arrays (coordinates) that label eachpoint (e.g., 1-dimensional arrays of numbers, datetime objects orstrings)

  • attrs: an OrderedDict to hold arbitrary metadata (attributes)

xarray uses dims and coords to enable its core metadata aware operations.Dimensions provide names that xarray uses instead of the axis argument foundin many numpy functions. Coordinates enable fast label based indexing andalignment, building on the functionality of the index found on a pandasDataFrame or Series.

DataArray objects also can have a name and can hold arbitrary metadata inthe form of their attrs property (an ordered dictionary). Names andattributes are strictly for users and user-written code: xarray makes no attemptto interpret them, and propagates them only in unambiguous cases (see FAQ,What is your approach to metadata?).

Creating a DataArray

The DataArray constructor takes:

  • data: a multi-dimensional array of values (e.g., a numpy ndarray,Series, DataFrame or Panel)

  • coords: a list or dictionary of coordinates. If a list, it should be alist of tuples where the first element is the dimension name and the secondelement is the corresponding coordinate array_like object.

  • dims: a list of dimension names. If omitted and coords is a list oftuples, dimension names are taken from coords.

  • attrs: a dictionary of attributes to add to the instance

  • name: a string that names the instance

  1. In [1]: data = np.random.rand(4, 3)
  2.  
  3. In [2]: locs = ['IA', 'IL', 'IN']
  4.  
  5. In [3]: times = pd.date_range('2000-01-01', periods=4)
  6.  
  7. In [4]: foo = xr.DataArray(data, coords=[times, locs], dims=['time', 'space'])
  8.  
  9. In [5]: foo
  10. Out[5]:
  11. <xarray.DataArray (time: 4, space: 3)>
  12. array([[0.12697 , 0.966718, 0.260476],
  13. [0.897237, 0.37675 , 0.336222],
  14. [0.451376, 0.840255, 0.123102],
  15. [0.543026, 0.373012, 0.447997]])
  16. Coordinates:
  17. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  18. * space (space) <U2 'IA' 'IL' 'IN'

Only data is required; all of other arguments will be filledin with default values:

  1. In [6]: xr.DataArray(data)
  2. Out[6]:
  3. <xarray.DataArray (dim_0: 4, dim_1: 3)>
  4. array([[0.12697 , 0.966718, 0.260476],
  5. [0.897237, 0.37675 , 0.336222],
  6. [0.451376, 0.840255, 0.123102],
  7. [0.543026, 0.373012, 0.447997]])
  8. Dimensions without coordinates: dim_0, dim_1

As you can see, dimension names are always present in the xarray data model: ifyou do not provide them, defaults of the form dim_N will be created.However, coordinates are always optional, and dimensions do not have automaticcoordinate labels.

Note

This is different from pandas, where axes always have tick labels, whichdefault to the integers [0, …, n-1].

Prior to xarray v0.9, xarray copied this behavior: default coordinates foreach dimension would be created if coordinates were not supplied explicitly.This is no longer the case.

Coordinates can be specified in the following ways:

  • A list of values with length equal to the number of dimensions, providingcoordinate labels for each dimension. Each value must be of one of thefollowing forms:

    • A DataArray or Variable

    • A tuple of the form (dims, data[, attrs]), which is converted intoarguments for Variable

    • A pandas object or scalar value, which is converted into a DataArray

    • A 1D array or list, which is interpreted as values for a one dimensionalcoordinate variable along the same dimension as it’s name

  • A dictionary of {coord_name: coord} where values are of the same formas the list. Supplying coordinates as a dictionary allows other coordinatesthan those corresponding to dimensions (more on these later). If you supplycoords as a dictionary, you must explicitly provide dims.

As a list of tuples:

  1. In [7]: xr.DataArray(data, coords=[('time', times), ('space', locs)])
  2. Out[7]:
  3. <xarray.DataArray (time: 4, space: 3)>
  4. array([[0.12697 , 0.966718, 0.260476],
  5. [0.897237, 0.37675 , 0.336222],
  6. [0.451376, 0.840255, 0.123102],
  7. [0.543026, 0.373012, 0.447997]])
  8. Coordinates:
  9. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  10. * space (space) <U2 'IA' 'IL' 'IN'

As a dictionary:

  1. In [8]: xr.DataArray(data, coords={'time': times, 'space': locs, 'const': 42,
  2. ...: 'ranking': ('space', [1, 2, 3])},
  3. ...: dims=['time', 'space'])
  4. ...:
  5. Out[8]:
  6. <xarray.DataArray (time: 4, space: 3)>
  7. array([[0.12697 , 0.966718, 0.260476],
  8. [0.897237, 0.37675 , 0.336222],
  9. [0.451376, 0.840255, 0.123102],
  10. [0.543026, 0.373012, 0.447997]])
  11. Coordinates:
  12. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  13. * space (space) <U2 'IA' 'IL' 'IN'
  14. const int64 42
  15. ranking (space) int64 1 2 3

As a dictionary with coords across multiple dimensions:

  1. In [9]: xr.DataArray(data, coords={'time': times, 'space': locs, 'const': 42,
  2. ...: 'ranking': (('time', 'space'), np.arange(12).reshape(4,3))},
  3. ...: dims=['time', 'space'])
  4. ...:
  5. Out[9]:
  6. <xarray.DataArray (time: 4, space: 3)>
  7. array([[0.12697 , 0.966718, 0.260476],
  8. [0.897237, 0.37675 , 0.336222],
  9. [0.451376, 0.840255, 0.123102],
  10. [0.543026, 0.373012, 0.447997]])
  11. Coordinates:
  12. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  13. * space (space) <U2 'IA' 'IL' 'IN'
  14. const int64 42
  15. ranking (time, space) int64 0 1 2 3 4 5 6 7 8 9 10 11

If you create a DataArray by supplying a pandasSeries, DataFrame orPanel, any non-specified arguments in theDataArray constructor will be filled in from the pandas object:

  1. In [10]: df = pd.DataFrame({'x': [0, 1], 'y': [2, 3]}, index=['a', 'b'])
  2.  
  3. In [11]: df.index.name = 'abc'
  4.  
  5. In [12]: df.columns.name = 'xyz'
  6.  
  7. In [13]: df
  8. Out[13]:
  9. xyz x y
  10. abc
  11. a 0 2
  12. b 1 3
  13.  
  14. In [14]: xr.DataArray(df)
  15. Out[14]:
  16. <xarray.DataArray (abc: 2, xyz: 2)>
  17. array([[0, 2],
  18. [1, 3]])
  19. Coordinates:
  20. * abc (abc) object 'a' 'b'
  21. * xyz (xyz) object 'x' 'y'

DataArray properties

Let’s take a look at the important properties on our array:

  1. In [15]: foo.values
  2. Out[15]:
  3. array([[0.127, 0.967, 0.26 ],
  4. [0.897, 0.377, 0.336],
  5. [0.451, 0.84 , 0.123],
  6. [0.543, 0.373, 0.448]])
  7.  
  8. In [16]: foo.dims
  9. Out[16]: ('time', 'space')
  10.  
  11. In [17]: foo.coords
  12. Out[17]:
  13. Coordinates:
  14. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  15. * space (space) <U2 'IA' 'IL' 'IN'
  16.  
  17. In [18]: foo.attrs
  18. Out[18]: OrderedDict()
  19.  
  20. In [19]: print(foo.name)
  21. None

You can modify values inplace:

  1. In [20]: foo.values = 1.0 * foo.values

Note

The array values in a DataArray have a single(homogeneous) data type. To work with heterogeneous or structured datatypes in xarray, use coordinates, or put separate DataArray objectsin a single Dataset (see below).

Now fill in some of that missing metadata:

  1. In [21]: foo.name = 'foo'
  2.  
  3. In [22]: foo.attrs['units'] = 'meters'
  4.  
  5. In [23]: foo
  6. Out[23]:
  7. <xarray.DataArray 'foo' (time: 4, space: 3)>
  8. array([[0.12697 , 0.966718, 0.260476],
  9. [0.897237, 0.37675 , 0.336222],
  10. [0.451376, 0.840255, 0.123102],
  11. [0.543026, 0.373012, 0.447997]])
  12. Coordinates:
  13. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  14. * space (space) <U2 'IA' 'IL' 'IN'
  15. Attributes:
  16. units: meters

The rename() method is another option, returning anew data array:

  1. In [24]: foo.rename('bar')
  2. Out[24]:
  3. <xarray.DataArray 'bar' (time: 4, space: 3)>
  4. array([[0.12697 , 0.966718, 0.260476],
  5. [0.897237, 0.37675 , 0.336222],
  6. [0.451376, 0.840255, 0.123102],
  7. [0.543026, 0.373012, 0.447997]])
  8. Coordinates:
  9. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  10. * space (space) <U2 'IA' 'IL' 'IN'
  11. Attributes:
  12. units: meters

DataArray Coordinates

The coords property is dict like. Individual coordinates can beaccessed from the coordinates by name, or even by indexing the data arrayitself:

  1. In [25]: foo.coords['time']
  2. Out[25]:
  3. <xarray.DataArray 'time' (time: 4)>
  4. array(['2000-01-01T00:00:00.000000000', '2000-01-02T00:00:00.000000000',
  5. '2000-01-03T00:00:00.000000000', '2000-01-04T00:00:00.000000000'],
  6. dtype='datetime64[ns]')
  7. Coordinates:
  8. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  9.  
  10. In [26]: foo['time']
  11. Out[26]:
  12. <xarray.DataArray 'time' (time: 4)>
  13. array(['2000-01-01T00:00:00.000000000', '2000-01-02T00:00:00.000000000',
  14. '2000-01-03T00:00:00.000000000', '2000-01-04T00:00:00.000000000'],
  15. dtype='datetime64[ns]')
  16. Coordinates:
  17. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04

These are also DataArray objects, which contain tick-labelsfor each dimension.

Coordinates can also be set or removed by using the dictionary like syntax:

  1. In [27]: foo['ranking'] = ('space', [1, 2, 3])
  2.  
  3. In [28]: foo.coords
  4. Out[28]:
  5. Coordinates:
  6. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  7. * space (space) <U2 'IA' 'IL' 'IN'
  8. ranking (space) int64 1 2 3
  9.  
  10. In [29]: del foo['ranking']
  11.  
  12. In [30]: foo.coords
  13. Out[30]:
  14. Coordinates:
  15. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  16. * space (space) <U2 'IA' 'IL' 'IN'

For more details, see Coordinates below.

Dataset

xarray.Dataset is xarray’s multi-dimensional equivalent of aDataFrame. It is a dict-likecontainer of labeled arrays (DataArray objects) with aligneddimensions. It is designed as an in-memory representation of the data modelfrom the netCDF file format.

In addition to the dict-like interface of the dataset itself, which can be usedto access any variable in a dataset, datasets have four key properties:

  • dims: a dictionary mapping from dimension names to the fixed length ofeach dimension (e.g., {'x': 6, 'y': 6, 'time': 8})

  • data_vars: a dict-like container of DataArrays corresponding to variables

  • coords: another dict-like container of DataArrays intended to label pointsused in data_vars (e.g., arrays of numbers, datetime objects or strings)

  • attrs: an OrderedDict to hold arbitrary metadata

The distinction between whether a variables falls in data or coordinates(borrowed from CF conventions) is mostly semantic, and you can probably getaway with ignoring it if you like: dictionary like access on a dataset willsupply variables found in either category. However, xarray does make use of thedistinction for indexing and computations. Coordinates indicateconstant/fixed/independent quantities, unlike the varying/measured/dependentquantities that belong in data.

Here is an example of how we might structure a dataset for a weather forecast:_images/dataset-diagram.pngIn this example, it would be natural to call temperature andprecipitation “data variables” and all the other arrays “coordinatevariables” because they label the points along the dimensions. (see 1 formore background on this example).

Creating a Dataset

To make an Dataset from scratch, supply dictionaries for anyvariables (data_vars), coordinates (coords) and attributes (attrs).

  • data_vars should be a dictionary with each key as the name of the variableand each value as one of:

    • A DataArray or Variable

    • A tuple of the form (dims, data[, attrs]), which is converted intoarguments for Variable

    • A pandas object, which is converted into a DataArray

    • A 1D array or list, which is interpreted as values for a one dimensionalcoordinate variable along the same dimension as it’s name

  • coords should be a dictionary of the same form as data_vars.

  • attrs should be a dictionary.

Let’s create some fake data for the example we show above:

  1. In [31]: temp = 15 + 8 * np.random.randn(2, 2, 3)
  2.  
  3. In [32]: precip = 10 * np.random.rand(2, 2, 3)
  4.  
  5. In [33]: lon = [[-99.83, -99.32], [-99.79, -99.23]]
  6.  
  7. In [34]: lat = [[42.25, 42.21], [42.63, 42.59]]
  8.  
  9. # for real use cases, its good practice to supply array attributes such as
  10. # units, but we won't bother here for the sake of brevity
  11. In [35]: ds = xr.Dataset({'temperature': (['x', 'y', 'time'], temp),
  12. ....: 'precipitation': (['x', 'y', 'time'], precip)},
  13. ....: coords={'lon': (['x', 'y'], lon),
  14. ....: 'lat': (['x', 'y'], lat),
  15. ....: 'time': pd.date_range('2014-09-06', periods=3),
  16. ....: 'reference_time': pd.Timestamp('2014-09-05')})
  17. ....:
  18.  
  19. In [36]: ds
  20. Out[36]:
  21. <xarray.Dataset>
  22. Dimensions: (time: 3, x: 2, y: 2)
  23. Coordinates:
  24. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  25. lat (x, y) float64 42.25 42.21 42.63 42.59
  26. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  27. reference_time datetime64[ns] 2014-09-05
  28. Dimensions without coordinates: x, y
  29. Data variables:
  30. temperature (x, y, time) float64 11.04 23.57 20.77 ... 6.301 9.61 15.91
  31. precipitation (x, y, time) float64 5.904 2.453 3.404 ... 3.435 1.709 3.947

Here we pass xarray.DataArray objects or a pandas object as valuesin the dictionary:

  1. In [37]: xr.Dataset({'bar': foo})
  2. Out[37]:
  3. <xarray.Dataset>
  4. Dimensions: (space: 3, time: 4)
  5. Coordinates:
  6. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  7. * space (space) <U2 'IA' 'IL' 'IN'
  8. Data variables:
  9. bar (time, space) float64 0.127 0.9667 0.2605 ... 0.543 0.373 0.448
  1. In [38]: xr.Dataset({'bar': foo.to_pandas()})
  2. Out[38]:
  3. <xarray.Dataset>
  4. Dimensions: (space: 3, time: 4)
  5. Coordinates:
  6. * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  7. * space (space) object 'IA' 'IL' 'IN'
  8. Data variables:
  9. bar (time, space) float64 0.127 0.9667 0.2605 ... 0.543 0.373 0.448

Where a pandas object is supplied as a value, the names of its indexes are used as dimensionnames, and its data is aligned to any existing dimensions.

You can also create an dataset from:

Dataset contents

Dataset implements the Python mapping interface, withvalues given by xarray.DataArray objects:

  1. In [39]: 'temperature' in ds
  2. Out[39]: True
  3.  
  4. In [40]: ds['temperature']
  5. Out[40]:
  6. <xarray.DataArray 'temperature' (x: 2, y: 2, time: 3)>
  7. array([[[11.040566, 23.57443 , 20.772441],
  8. [ 9.345831, 6.6834 , 17.174879]],
  9.  
  10. [[11.600221, 19.536163, 17.209856],
  11. [ 6.300794, 9.610482, 15.909187]]])
  12. Coordinates:
  13. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  14. lat (x, y) float64 42.25 42.21 42.63 42.59
  15. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  16. reference_time datetime64[ns] 2014-09-05
  17. Dimensions without coordinates: x, y

Valid keys include each listed coordinate and data variable.

Data and coordinate variables are also contained separately in thedata_vars and coordsdictionary-like attributes:

  1. In [41]: ds.data_vars
  2. Out[41]:
  3. Data variables:
  4. temperature (x, y, time) float64 11.04 23.57 20.77 ... 6.301 9.61 15.91
  5. precipitation (x, y, time) float64 5.904 2.453 3.404 ... 3.435 1.709 3.947
  6.  
  7. In [42]: ds.coords
  8. Out[42]:
  9. Coordinates:
  10. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  11. lat (x, y) float64 42.25 42.21 42.63 42.59
  12. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  13. reference_time datetime64[ns] 2014-09-05

Finally, like data arrays, datasets also store arbitrary metadata in the formof attributes:

  1. In [43]: ds.attrs
  2. Out[43]: OrderedDict()
  3.  
  4. In [44]: ds.attrs['title'] = 'example attribute'
  5.  
  6. In [45]: ds
  7. Out[45]:
  8. <xarray.Dataset>
  9. Dimensions: (time: 3, x: 2, y: 2)
  10. Coordinates:
  11. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  12. lat (x, y) float64 42.25 42.21 42.63 42.59
  13. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  14. reference_time datetime64[ns] 2014-09-05
  15. Dimensions without coordinates: x, y
  16. Data variables:
  17. temperature (x, y, time) float64 11.04 23.57 20.77 ... 6.301 9.61 15.91
  18. precipitation (x, y, time) float64 5.904 2.453 3.404 ... 3.435 1.709 3.947
  19. Attributes:
  20. title: example attribute

xarray does not enforce any restrictions on attributes, but serialization tosome file formats may fail if you use objects that are not strings, numbersor numpy.ndarray objects.

As a useful shortcut, you can use attribute style access for reading (but notsetting) variables and attributes:

  1. In [46]: ds.temperature
  2. Out[46]:
  3. <xarray.DataArray 'temperature' (x: 2, y: 2, time: 3)>
  4. array([[[11.040566, 23.57443 , 20.772441],
  5. [ 9.345831, 6.6834 , 17.174879]],
  6.  
  7. [[11.600221, 19.536163, 17.209856],
  8. [ 6.300794, 9.610482, 15.909187]]])
  9. Coordinates:
  10. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  11. lat (x, y) float64 42.25 42.21 42.63 42.59
  12. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  13. reference_time datetime64[ns] 2014-09-05
  14. Dimensions without coordinates: x, y

This is particularly useful in an exploratory context, because you cantab-complete these variable names with tools like IPython.

Dictionary like methods

We can update a dataset in-place using Python’s standard dictionary syntax. Forexample, to create this example dataset from scratch, we could have written:

  1. In [47]: ds = xr.Dataset()
  2.  
  3. In [48]: ds['temperature'] = (('x', 'y', 'time'), temp)
  4.  
  5. In [49]: ds['temperature_double'] = (('x', 'y', 'time'), temp * 2 )
  6.  
  7. In [50]: ds['precipitation'] = (('x', 'y', 'time'), precip)
  8.  
  9. In [51]: ds.coords['lat'] = (('x', 'y'), lat)
  10.  
  11. In [52]: ds.coords['lon'] = (('x', 'y'), lon)
  12.  
  13. In [53]: ds.coords['time'] = pd.date_range('2014-09-06', periods=3)
  14.  
  15. In [54]: ds.coords['reference_time'] = pd.Timestamp('2014-09-05')

To change the variables in a Dataset, you can use all the standard dictionarymethods, including values, items, delitem, get andupdate(). Note that assigning a DataArray or pandasobject to a Dataset variable using setitem or update willautomatically align the array(s) to the originaldataset’s indexes.

You can copy a Dataset by calling the copy()method. By default, the copy is shallow, so only the container will be copied:the arrays in the Dataset will still be stored in the same underlyingnumpy.ndarray objects. You can copy all data by callingds.copy(deep=True).

Transforming datasets

In addition to dictionary-like methods (described above), xarray has additionalmethods (like pandas) for transforming datasets into new objects.

For removing variables, you can select and drop an explicit list ofvariables by indexing with a list of names or using thedrop() methods to return a new Dataset. Theseoperations keep around coordinates:

  1. In [55]: ds[['temperature']]
  2. Out[55]:
  3. <xarray.Dataset>
  4. Dimensions: (time: 3, x: 2, y: 2)
  5. Coordinates:
  6. reference_time datetime64[ns] 2014-09-05
  7. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  8. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  9. lat (x, y) float64 42.25 42.21 42.63 42.59
  10. Dimensions without coordinates: x, y
  11. Data variables:
  12. temperature (x, y, time) float64 11.04 23.57 20.77 ... 6.301 9.61 15.91
  13.  
  14. In [56]: ds[['temperature', 'temperature_double']]
  15. Out[56]:
  16. <xarray.Dataset>
  17. Dimensions: (time: 3, x: 2, y: 2)
  18. Coordinates:
  19. reference_time datetime64[ns] 2014-09-05
  20. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  21. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  22. lat (x, y) float64 42.25 42.21 42.63 42.59
  23. Dimensions without coordinates: x, y
  24. Data variables:
  25. temperature (x, y, time) float64 11.04 23.57 20.77 ... 9.61 15.91
  26. temperature_double (x, y, time) float64 22.08 47.15 41.54 ... 19.22 31.82
  27.  
  28. In [57]: ds.drop('temperature')
  29. Out[57]:
  30. <xarray.Dataset>
  31. Dimensions: (time: 3, x: 2, y: 2)
  32. Coordinates:
  33. lat (x, y) float64 42.25 42.21 42.63 42.59
  34. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  35. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  36. reference_time datetime64[ns] 2014-09-05
  37. Dimensions without coordinates: x, y
  38. Data variables:
  39. temperature_double (x, y, time) float64 22.08 47.15 41.54 ... 19.22 31.82
  40. precipitation (x, y, time) float64 5.904 2.453 3.404 ... 1.709 3.947

To remove a dimension, you can use drop_dims() method.Any variables using that dimension are dropped:

  1. In [58]: ds.drop_dims('time')
  2. Out[58]:
  3. <xarray.Dataset>
  4. Dimensions: (x: 2, y: 2)
  5. Coordinates:
  6. lat (x, y) float64 42.25 42.21 42.63 42.59
  7. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  8. reference_time datetime64[ns] 2014-09-05
  9. Dimensions without coordinates: x, y
  10. Data variables:
  11. *empty*

As an alternate to dictionary-like modifications, you can useassign() and assign_coords().These methods return a new dataset with additional (or replaced) or values:

  1. In [59]: ds.assign(temperature2 = 2 * ds.temperature)
  2. Out[59]:
  3. <xarray.Dataset>
  4. Dimensions: (time: 3, x: 2, y: 2)
  5. Coordinates:
  6. lat (x, y) float64 42.25 42.21 42.63 42.59
  7. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  8. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  9. reference_time datetime64[ns] 2014-09-05
  10. Dimensions without coordinates: x, y
  11. Data variables:
  12. temperature (x, y, time) float64 11.04 23.57 20.77 ... 9.61 15.91
  13. temperature_double (x, y, time) float64 22.08 47.15 41.54 ... 19.22 31.82
  14. precipitation (x, y, time) float64 5.904 2.453 3.404 ... 1.709 3.947
  15. temperature2 (x, y, time) float64 22.08 47.15 41.54 ... 19.22 31.82

There is also the pipe() method that allows you to usea method call with an external function (e.g., ds.pipe(func)) instead ofsimply calling it (e.g., func(ds)). This allows you to write pipelines fortransforming you data (using “method chaining”) instead of writing hard tofollow nested function calls:

  1. # these lines are equivalent, but with pipe we can make the logic flow
  2. # entirely from left to right
  3. In [60]: plt.plot((2 * ds.temperature.sel(x=0)).mean('y'))
  4. Out[60]: [<matplotlib.lines.Line2D at 0x7f3425bb25c0>]
  5.  
  6. In [61]: (ds.temperature
  7. ....: .sel(x=0)
  8. ....: .pipe(lambda x: 2 * x)
  9. ....: .mean('y')
  10. ....: .pipe(plt.plot))
  11. ....:
  12. Out[61]: [<matplotlib.lines.Line2D at 0x7f3425bb2a20>]

Both pipe and assign replicate the pandas methods of the same names(DataFrame.pipe andDataFrame.assign).

With xarray, there is no performance penalty for creating new datasets, even ifvariables are lazily loaded from a file on disk. Creating new objects insteadof mutating existing objects often results in easier to understand code, so weencourage using this approach.

Renaming variables

Another useful option is the rename() method to renamedataset variables:

  1. In [62]: ds.rename({'temperature': 'temp', 'precipitation': 'precip'})
  2. Out[62]:
  3. <xarray.Dataset>
  4. Dimensions: (time: 3, x: 2, y: 2)
  5. Coordinates:
  6. lat (x, y) float64 42.25 42.21 42.63 42.59
  7. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  8. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  9. reference_time datetime64[ns] 2014-09-05
  10. Dimensions without coordinates: x, y
  11. Data variables:
  12. temp (x, y, time) float64 11.04 23.57 20.77 ... 9.61 15.91
  13. temperature_double (x, y, time) float64 22.08 47.15 41.54 ... 19.22 31.82
  14. precip (x, y, time) float64 5.904 2.453 3.404 ... 1.709 3.947

The related swap_dims() method allows you do to swapdimension and non-dimension variables:

  1. In [63]: ds.coords['day'] = ('time', [6, 7, 8])
  2.  
  3. In [64]: ds.swap_dims({'time': 'day'})
  4. Out[64]:
  5. <xarray.Dataset>
  6. Dimensions: (day: 3, x: 2, y: 2)
  7. Coordinates:
  8. lat (x, y) float64 42.25 42.21 42.63 42.59
  9. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  10. time (day) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  11. reference_time datetime64[ns] 2014-09-05
  12. * day (day) int64 6 7 8
  13. Dimensions without coordinates: x, y
  14. Data variables:
  15. temperature (x, y, day) float64 11.04 23.57 20.77 ... 9.61 15.91
  16. temperature_double (x, y, day) float64 22.08 47.15 41.54 ... 19.22 31.82
  17. precipitation (x, y, day) float64 5.904 2.453 3.404 ... 1.709 3.947

Coordinates

Coordinates are ancillary variables stored for DataArray and Datasetobjects in the coords attribute:

  1. In [65]: ds.coords
  2. Out[65]:
  3. Coordinates:
  4. lat (x, y) float64 42.25 42.21 42.63 42.59
  5. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  6. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  7. reference_time datetime64[ns] 2014-09-05
  8. day (time) int64 6 7 8

Unlike attributes, xarray does interpret and persist coordinates inoperations that transform xarray objects. There are two types of coordinatesin xarray:

  • dimension coordinates are one dimensional coordinates with a name equalto their sole dimension (marked by * when printing a dataset or dataarray). They are used for label based indexing and alignment,like the index found on a pandas DataFrame orSeries. Indeed, these “dimension” coordinates use apandas.Index internally to store their values.

  • non-dimension coordinates are variables that contain coordinatedata, but are not a dimension coordinate. They can be multidimensional(see Working with Multidimensional Coordinates), and there is no relationship between thename of a non-dimension coordinate and the name(s) of its dimension(s).Non-dimension coordinates can be useful for indexing or plotting; otherwise,xarray does not make any direct use of the values associated with them.They are not used for alignment or automatic indexing, nor are they requiredto match when doing arithmetic(see Coordinates).

Note

xarray’s terminology differs from the CF terminology, where the“dimension coordinates” are called “coordinate variables”, and the“non-dimension coordinates” are called “auxiliary coordinate variables”(see GH1295 for more details).

Modifying coordinates

To entirely add or remove coordinate arrays, you can use dictionary likesyntax, as shown above.

To convert back and forth between data and coordinates, you can use theset_coords() andreset_coords() methods:

  1. In [66]: ds.reset_coords()
  2. Out[66]:
  3. <xarray.Dataset>
  4. Dimensions: (time: 3, x: 2, y: 2)
  5. Coordinates:
  6. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  7. Dimensions without coordinates: x, y
  8. Data variables:
  9. temperature (x, y, time) float64 11.04 23.57 20.77 ... 9.61 15.91
  10. temperature_double (x, y, time) float64 22.08 47.15 41.54 ... 19.22 31.82
  11. precipitation (x, y, time) float64 5.904 2.453 3.404 ... 1.709 3.947
  12. lat (x, y) float64 42.25 42.21 42.63 42.59
  13. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  14. reference_time datetime64[ns] 2014-09-05
  15. day (time) int64 6 7 8
  16.  
  17. In [67]: ds.set_coords(['temperature', 'precipitation'])
  18. Out[67]:
  19. <xarray.Dataset>
  20. Dimensions: (time: 3, x: 2, y: 2)
  21. Coordinates:
  22. temperature (x, y, time) float64 11.04 23.57 20.77 ... 9.61 15.91
  23. precipitation (x, y, time) float64 5.904 2.453 3.404 ... 1.709 3.947
  24. lat (x, y) float64 42.25 42.21 42.63 42.59
  25. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  26. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  27. reference_time datetime64[ns] 2014-09-05
  28. day (time) int64 6 7 8
  29. Dimensions without coordinates: x, y
  30. Data variables:
  31. temperature_double (x, y, time) float64 22.08 47.15 41.54 ... 19.22 31.82
  32.  
  33. In [68]: ds['temperature'].reset_coords(drop=True)
  34. Out[68]:
  35. <xarray.DataArray 'temperature' (x: 2, y: 2, time: 3)>
  36. array([[[11.040566, 23.57443 , 20.772441],
  37. [ 9.345831, 6.6834 , 17.174879]],
  38.  
  39. [[11.600221, 19.536163, 17.209856],
  40. [ 6.300794, 9.610482, 15.909187]]])
  41. Coordinates:
  42. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  43. Dimensions without coordinates: x, y

Notice that these operations skip coordinates with names given by dimensions,as used for indexing. This mostly because we are not entirely sure how todesign the interface around the fact that xarray cannot store a coordinate andvariable with the name but different values in the same dictionary. But we dorecognize that supporting something like this would be useful.

Coordinates methods

Coordinates objects also have a few useful methods, mostly for convertingthem into dataset objects:

  1. In [69]: ds.coords.to_dataset()
  2. Out[69]:
  3. <xarray.Dataset>
  4. Dimensions: (time: 3, x: 2, y: 2)
  5. Coordinates:
  6. lat (x, y) float64 42.25 42.21 42.63 42.59
  7. reference_time datetime64[ns] 2014-09-05
  8. lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
  9. day (time) int64 6 7 8
  10. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  11. Dimensions without coordinates: x, y
  12. Data variables:
  13. *empty*

The merge method is particularly interesting, because it implements the samelogic used for merging coordinates in arithmetic operations(see Computation):

  1. In [70]: alt = xr.Dataset(coords={'z': [10], 'lat': 0, 'lon': 0})
  2.  
  3. In [71]: ds.coords.merge(alt.coords)
  4. Out[71]:
  5. <xarray.Dataset>
  6. Dimensions: (time: 3, z: 1)
  7. Coordinates:
  8. * time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
  9. reference_time datetime64[ns] 2014-09-05
  10. day (time) int64 6 7 8
  11. * z (z) int64 10
  12. Data variables:
  13. *empty*

The coords.merge method may be useful if you want to implement your ownbinary operations that act on xarray objects. In the future, we hope to writemore helper functions so that you can easily make your functions act likexarray’s built-in arithmetic.

Indexes

To convert a coordinate (or any DataArray) into an actualpandas.Index, use the to_index() method:

  1. In [72]: ds['time'].to_index()
  2. Out[72]: DatetimeIndex(['2014-09-06', '2014-09-07', '2014-09-08'], dtype='datetime64[ns]', name='time', freq='D')

A useful shortcut is the indexes property (on both DataArray andDataset), which lazily constructs a dictionary whose keys are given by eachdimension and whose the values are Index objects:

  1. In [73]: ds.indexes
  2. Out[73]: time: DatetimeIndex(['2014-09-06', '2014-09-07', '2014-09-08'], dtype='datetime64[ns]', name='time', freq='D')

MultiIndex coordinates

Xarray supports labeling coordinate values with a pandas.MultiIndex:

  1. In [74]: midx = pd.MultiIndex.from_arrays([['R', 'R', 'V', 'V'], [.1, .2, .7, .9]],
  2. ....: names=('band', 'wn'))
  3. ....:
  4.  
  5. In [75]: mda = xr.DataArray(np.random.rand(4), coords={'spec': midx}, dims='spec')
  6.  
  7. In [76]: mda
  8. Out[76]:
  9. <xarray.DataArray (spec: 4)>
  10. array([0.641666, 0.274592, 0.462354, 0.871372])
  11. Coordinates:
  12. * spec (spec) MultiIndex
  13. - band (spec) object 'R' 'R' 'V' 'V'
  14. - wn (spec) float64 0.1 0.2 0.7 0.9

For convenience multi-index levels are directly accessible as “virtual” or“derived” coordinates (marked by - when printing a dataset or data array):

  1. In [77]: mda['band']
  2. Out[77]:
  3. <xarray.DataArray 'band' (spec: 4)>
  4. array(['R', 'R', 'V', 'V'], dtype=object)
  5. Coordinates:
  6. * spec (spec) MultiIndex
  7. - band (spec) object 'R' 'R' 'V' 'V'
  8. - wn (spec) float64 0.1 0.2 0.7 0.9
  9.  
  10. In [78]: mda.wn
  11. Out[78]:
  12. <xarray.DataArray 'wn' (spec: 4)>
  13. array([0.1, 0.2, 0.7, 0.9])
  14. Coordinates:
  15. * spec (spec) MultiIndex
  16. - band (spec) object 'R' 'R' 'V' 'V'
  17. - wn (spec) float64 0.1 0.2 0.7 0.9

Indexing with multi-index levels is also possible using the sel method(see Multi-level indexing).

Unlike other coordinates, “virtual” level coordinates are not stored inthe coords attribute of DataArray and Dataset objects(although they are shown when printing the coords attribute).Consequently, most of the coordinates related methods don’t apply for them.It also can’t be used to replace one particular level.

Because in a DataArray or Dataset object each multi-index level isaccessible as a “virtual” coordinate, its name must not conflict with the namesof the other levels, coordinates and data variables of the same object.Even though Xarray set default names for multi-indexes with unnamed levels,it is recommended that you explicitly set the names of the levels.

  • 1
  • Latitude and longitude are 2D arrays because the dataset usesprojected coordinates. reference_time refers to the reference timeat which the forecast was made, rather than time which is the valid timefor which the forecast applies.