Data Structures (original) (raw)

DataArray#

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

Xarray uses dims and coords to enable its core metadata aware operations. Dimensions provide names that xarray uses instead of the axis argument found in many numpy functions. Coordinates enable fast label based indexing and alignment, 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 in the form of their attrs property. Names and attributes are strictly for users and user-written code: xarray makes no attempt to interpret them, and propagates them only in unambiguous cases. For reading and writing attributes xarray relies on the capabilities of the supported backends. (see FAQ, What is your approach to metadata?).

Creating a DataArray#

The DataArray constructor takes:

In [1]: data = np.random.rand(4, 3)

In [2]: locs = ["IA", "IL", "IN"]

In [3]: times = pd.date_range("2000-01-01", periods=4)

In [4]: foo = xr.DataArray(data, coords=[times, locs], dims=["time", "space"])

In [5]: foo Out[5]: <xarray.DataArray (time: 4, space: 3)> Size: 96B array([[0.127, 0.967, 0.26 ], [0.897, 0.377, 0.336], [0.451, 0.84 , 0.123], [0.543, 0.373, 0.448]], shape=(4, 3)) Coordinates:

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

In [6]: xr.DataArray(data) Out[6]: <xarray.DataArray (dim_0: 4, dim_1: 3)> Size: 96B array([[0.127, 0.967, 0.26 ], [0.897, 0.377, 0.336], [0.451, 0.84 , 0.123], [0.543, 0.373, 0.448]], shape=(4, 3)) Dimensions without coordinates: dim_0, dim_1

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

Note

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

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

Coordinates can be specified in the following ways:

As a list of tuples:

In [7]: xr.DataArray(data, coords=[("time", times), ("space", locs)]) Out[7]: <xarray.DataArray (time: 4, space: 3)> Size: 96B array([[0.127, 0.967, 0.26 ], [0.897, 0.377, 0.336], [0.451, 0.84 , 0.123], [0.543, 0.373, 0.448]], shape=(4, 3)) Coordinates:

As a dictionary:

In [8]: xr.DataArray( ...: data, ...: coords={ ...: "time": times, ...: "space": locs, ...: "const": 42, ...: "ranking": ("space", [1, 2, 3]), ...: }, ...: dims=["time", "space"], ...: ) ...: Out[8]: <xarray.DataArray (time: 4, space: 3)> Size: 96B array([[0.127, 0.967, 0.26 ], [0.897, 0.377, 0.336], [0.451, 0.84 , 0.123], [0.543, 0.373, 0.448]], shape=(4, 3)) Coordinates:

As a dictionary with coords across multiple dimensions:

In [9]: xr.DataArray( ...: data, ...: coords={ ...: "time": times, ...: "space": locs, ...: "const": 42, ...: "ranking": (("time", "space"), np.arange(12).reshape(4, 3)), ...: }, ...: dims=["time", "space"], ...: ) ...: Out[9]: <xarray.DataArray (time: 4, space: 3)> Size: 96B array([[0.127, 0.967, 0.26 ], [0.897, 0.377, 0.336], [0.451, 0.84 , 0.123], [0.543, 0.373, 0.448]], shape=(4, 3)) Coordinates:

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

In [10]: df = pd.DataFrame({"x": [0, 1], "y": [2, 3]}, index=["a", "b"])

In [11]: df.index.name = "abc"

In [12]: df.columns.name = "xyz"

In [13]: df Out[13]: xyz x y abc
a 0 2 b 1 3

In [14]: xr.DataArray(df) Out[14]: <xarray.DataArray (abc: 2, xyz: 2)> Size: 32B array([[0, 2], [1, 3]]) Coordinates:

DataArray properties#

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

In [15]: foo.values Out[15]: array([[0.127, 0.967, 0.26 ], [0.897, 0.377, 0.336], [0.451, 0.84 , 0.123], [0.543, 0.373, 0.448]], shape=(4, 3))

In [16]: foo.dims Out[16]: ('time', 'space')

In [17]: foo.coords Out[17]: Coordinates:

In [18]: foo.attrs Out[18]: {}

In [19]: print(foo.name) None

You can modify values inplace:

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 data types in xarray, use coordinates, or put separate DataArray objects in a single Dataset (see below).

Now fill in some of that missing metadata:

In [21]: foo.name = "foo"

In [22]: foo.attrs["units"] = "meters"

In [23]: foo Out[23]: <xarray.DataArray 'foo' (time: 4, space: 3)> Size: 96B array([[0.127, 0.967, 0.26 ], [0.897, 0.377, 0.336], [0.451, 0.84 , 0.123], [0.543, 0.373, 0.448]], shape=(4, 3)) Coordinates:

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

In [24]: foo.rename("bar") Out[24]: <xarray.DataArray 'bar' (time: 4, space: 3)> Size: 96B array([[0.127, 0.967, 0.26 ], [0.897, 0.377, 0.336], [0.451, 0.84 , 0.123], [0.543, 0.373, 0.448]], shape=(4, 3)) Coordinates:

DataArray Coordinates#

The coords property is dict like. Individual coordinates can be accessed from the coordinates by name, or even by indexing the data array itself:

In [25]: foo.coords["time"] Out[25]: <xarray.DataArray 'time' (time: 4)> Size: 32B array(['2000-01-01T00:00:00.000000000', '2000-01-02T00:00:00.000000000', '2000-01-03T00:00:00.000000000', '2000-01-04T00:00:00.000000000'], dtype='datetime64[ns]') Coordinates:

In [26]: foo["time"] Out[26]: <xarray.DataArray 'time' (time: 4)> Size: 32B array(['2000-01-01T00:00:00.000000000', '2000-01-02T00:00:00.000000000', '2000-01-03T00:00:00.000000000', '2000-01-04T00:00:00.000000000'], dtype='datetime64[ns]') Coordinates:

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

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

In [27]: foo["ranking"] = ("space", [1, 2, 3])

In [28]: foo.coords Out[28]: Coordinates:

In [29]: del foo["ranking"]

In [30]: foo.coords Out[30]: Coordinates:

For more details, see Coordinates below.

Dataset#

xarray.Dataset is xarray’s multi-dimensional equivalent of aDataFrame. It is a dict-like container of labeled arrays (DataArray objects) with aligned dimensions. It is designed as an in-memory representation of the data model from the netCDF file format.

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

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

Here is an example of how we might structure a dataset for a weather forecast:

../_images/dataset-diagram.png

In this example, it would be natural to call temperature andprecipitation “data variables” and all the other arrays “coordinate variables” because they label the points along the dimensions. (see [1] for more background on this example).

Creating a Dataset#

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

Let’s create some fake data for the example we show above. In this example dataset, we will represent measurements of the temperature and pressure that were made under various conditions:

In [31]: np.random.seed(0)

In [32]: temperature = 15 + 8 * np.random.randn(2, 3, 4)

In [33]: precipitation = 10 * np.random.rand(2, 3, 4)

In [34]: lon = [-99.83, -99.32]

In [35]: lat = [42.25, 42.21]

In [36]: instruments = ["manufac1", "manufac2", "manufac3"]

In [37]: time = pd.date_range("2014-09-06", periods=4)

In [38]: reference_time = pd.Timestamp("2014-09-05")

for real use cases, its good practice to supply array attributes such as

units, but we won't bother here for the sake of brevity

In [39]: ds = xr.Dataset( ....: { ....: "temperature": (["loc", "instrument", "time"], temperature), ....: "precipitation": (["loc", "instrument", "time"], precipitation), ....: }, ....: coords={ ....: "lon": (["loc"], lon), ....: "lat": (["loc"], lat), ....: "instrument": instruments, ....: "time": time, ....: "reference_time": reference_time, ....: }, ....: ) ....:

In [40]: ds Out[40]: <xarray.Dataset> Size: 552B Dimensions: (loc: 2, instrument: 3, time: 4) Coordinates: lon (loc) float64 16B -99.83 -99.32 lat (loc) float64 16B 42.25 42.21

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

In [41]: xr.Dataset(dict(bar=foo)) Out[41]: <xarray.Dataset> Size: 152B Dimensions: (time: 4, space: 3) Coordinates:

In [42]: xr.Dataset(dict(bar=foo.to_pandas())) Out[42]: <xarray.Dataset> Size: 152B Dimensions: (time: 4, space: 3) Coordinates:

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

You can also create an dataset from:

Dataset contents#

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

In [43]: "temperature" in ds Out[43]: True

In [44]: ds["temperature"] Out[44]: <xarray.DataArray 'temperature' (loc: 2, instrument: 3, time: 4)> Size: 192B array([[[29.112, 18.201, 22.83 , 32.927], [29.94 , 7.182, 22.601, 13.789], [14.174, 18.285, 16.152, 26.634]],

   [[21.088, 15.973, 18.551, 17.669],
    [26.953, 13.359, 17.505,  8.167],
    [-5.424, 20.229, 21.915,  9.063]]], shape=(2, 3, 4))

Coordinates: lon (loc) float64 16B -99.83 -99.32 lat (loc) float64 16B 42.25 42.21

Valid keys include each listed coordinate and data variable.

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

In [45]: ds.data_vars Out[45]: Data variables: temperature (loc, instrument, time) float64 192B 29.11 18.2 ... 9.063 precipitation (loc, instrument, time) float64 192B 4.562 5.684 ... 1.613

In [46]: ds.coords Out[46]: Coordinates: lon (loc) float64 16B -99.83 -99.32 lat (loc) float64 16B 42.25 42.21

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

In [47]: ds.attrs Out[47]: {}

In [48]: ds.attrs["title"] = "example attribute"

In [49]: ds Out[49]: <xarray.Dataset> Size: 552B Dimensions: (loc: 2, instrument: 3, time: 4) Coordinates: lon (loc) float64 16B -99.83 -99.32 lat (loc) float64 16B 42.25 42.21

Xarray does not enforce any restrictions on attributes, but serialization to some file formats may fail if you use objects that are not strings, numbers or numpy.ndarray objects.

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

In [50]: ds.temperature Out[50]: <xarray.DataArray 'temperature' (loc: 2, instrument: 3, time: 4)> Size: 192B array([[[29.112, 18.201, 22.83 , 32.927], [29.94 , 7.182, 22.601, 13.789], [14.174, 18.285, 16.152, 26.634]],

   [[21.088, 15.973, 18.551, 17.669],
    [26.953, 13.359, 17.505,  8.167],
    [-5.424, 20.229, 21.915,  9.063]]], shape=(2, 3, 4))

Coordinates: lon (loc) float64 16B -99.83 -99.32 lat (loc) float64 16B 42.25 42.21

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

Dictionary like methods#

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

In [51]: ds = xr.Dataset()

In [52]: ds["temperature"] = (("loc", "instrument", "time"), temperature)

In [53]: ds["temperature_double"] = (("loc", "instrument", "time"), temperature * 2)

In [54]: ds["precipitation"] = (("loc", "instrument", "time"), precipitation)

In [55]: ds.coords["lat"] = (("loc",), lat)

In [56]: ds.coords["lon"] = (("loc",), lon)

In [57]: ds.coords["time"] = pd.date_range("2014-09-06", periods=4)

In [58]: ds.coords["reference_time"] = pd.Timestamp("2014-09-05")

To change the variables in a Dataset, you can use all the standard dictionary methods, including values, items, __delitem__, get andupdate(). Note that assigning a DataArray or pandas object to a Dataset variable using __setitem__ or update willautomatically align the array(s) to the original dataset’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 additional methods (like pandas) for transforming datasets into new objects.

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

In [59]: ds[["temperature"]] Out[59]: <xarray.Dataset> Size: 264B Dimensions: (loc: 2, instrument: 3, time: 4) Coordinates: lat (loc) float64 16B 42.25 42.21 lon (loc) float64 16B -99.83 -99.32

In [60]: ds[["temperature", "temperature_double"]] Out[60]: <xarray.Dataset> Size: 456B Dimensions: (loc: 2, instrument: 3, time: 4) Coordinates: lat (loc) float64 16B 42.25 42.21 lon (loc) float64 16B -99.83 -99.32

In [61]: ds.drop_vars("temperature") Out[61]: <xarray.Dataset> Size: 456B Dimensions: (loc: 2, instrument: 3, time: 4) Coordinates: lat (loc) float64 16B 42.25 42.21 lon (loc) float64 16B -99.83 -99.32

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

In [62]: ds.drop_dims("time") Out[62]: <xarray.Dataset> Size: 40B Dimensions: (loc: 2) Coordinates: lat (loc) float64 16B 42.25 42.21 lon (loc) float64 16B -99.83 -99.32 reference_time datetime64[ns] 8B 2014-09-05 Dimensions without coordinates: loc Data variables: empty

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

In [63]: ds.assign(temperature2=2 * ds.temperature) Out[63]: <xarray.Dataset> Size: 840B Dimensions: (loc: 2, instrument: 3, time: 4) Coordinates: lat (loc) float64 16B 42.25 42.21 lon (loc) float64 16B -99.83 -99.32

There is also the pipe() method that allows you to use a method call with an external function (e.g., ds.pipe(func)) instead of simply calling it (e.g., func(ds)). This allows you to write pipelines for transforming your data (using “method chaining”) instead of writing hard to follow nested function calls:

these lines are equivalent, but with pipe we can make the logic flow

entirely from left to right

In [64]: plt.plot((2 * ds.temperature.sel(loc=0)).mean("instrument")) Out[64]: [<matplotlib.lines.Line2D at 0x73711726d590>]

In [65]: (ds.temperature.sel(loc=0).pipe(lambda x: 2 * x).mean("instrument").pipe(plt.plot)) Out[65]: [<matplotlib.lines.Line2D at 0x737117005950>]

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 if variables are lazily loaded from a file on disk. Creating new objects instead of mutating existing objects often results in easier to understand code, so we encourage using this approach.

Renaming variables#

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

In [66]: ds.rename({"temperature": "temp", "precipitation": "precip"}) Out[66]: <xarray.Dataset> Size: 648B Dimensions: (loc: 2, instrument: 3, time: 4) Coordinates: lat (loc) float64 16B 42.25 42.21 lon (loc) float64 16B -99.83 -99.32

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

In [67]: ds.coords["day"] = ("time", [6, 7, 8, 9])

In [68]: ds.swap_dims({"time": "day"}) Out[68]: <xarray.Dataset> Size: 680B Dimensions: (loc: 2, instrument: 3, day: 4) Coordinates: lat (loc) float64 16B 42.25 42.21 lon (loc) float64 16B -99.83 -99.32 time (day) datetime64[ns] 32B 2014-09-06 ... 2014-09-09 reference_time datetime64[ns] 8B 2014-09-05

DataTree#

DataTree is xarray’s highest-level data structure, able to organise heterogeneous data which could not be stored inside a singleDataset object. This includes representing the recursive structure of multiple groups within a netCDF file or Zarr Store.

Each DataTree object (or “node”) contains the same data that a singlexarray.Dataset would (i.e. DataArray objects stored under hashable keys), and so has the same key properties:

A single DataTree object acts much like a single Dataset object, and has a similar set of dict-like methods defined upon it. However, DataTrees can also contain other DataTree objects, so they can be thought of as nested dict-like containers of both xarray.DataArrays and DataTrees.

A single datatree object is known as a “node”, and its position relative to other nodes is defined by two more key properties:

Each child automatically knows about its parent node, and a node without a parent is known as a “root” node (represented by the parent attribute pointing to None). Nodes can have multiple children, but as each child node has at most one parent, there can only ever be one root node in a given tree.

The overall structure is technically a connected acyclic undirected rooted graph, otherwise known as a “Tree”.

DataTree objects can also optionally have a name as well as attrs, just like a DataArray. Again these are not normally used unless explicitly accessed by the user.

Creating a DataTree#

One way to create a DataTree from scratch is to create each node individually, specifying the nodes’ relationship to one another as you create each one.

The DataTree constructor takes:

Let’s make a single datatree node with some example data in it:

In [69]: ds1 = xr.Dataset({"foo": "orange"})

In [70]: dt = xr.DataTree(name="root", dataset=ds1)

In [71]: dt Out[71]: <xarray.DataTree 'root'> Group: / Dimensions: () Data variables: foo <U6 24B 'orange'

At this point we have created a single node datatree with no parent and no children.

In [72]: dt.parent is None Out[72]: True

In [73]: dt.children Out[73]: Frozen({})

We can add a second node to this tree, assigning it to the parent node dt:

In [74]: dataset2 = xr.Dataset({"bar": 0}, coords={"y": ("y", [0, 1, 2])})

In [75]: dt2 = xr.DataTree(name="a", dataset=dataset2)

Add the child Datatree to the root node

In [76]: dt.children = {"child-node": dt2}

In [77]: dt Out[77]: <xarray.DataTree 'root'> Group: / │ Dimensions: () │ Data variables: │ foo <U6 24B 'orange' └── Group: /child-node Dimensions: (y: 3) Coordinates: * y (y) int64 24B 0 1 2 Data variables: bar int64 8B 0

More idiomatically you can create a tree from a dictionary of Datasets andDataTrees. In this case we add a new node under dt["child-node"] by providing the explicit path under "child-node" as the dictionary key:

create a third Dataset

In [78]: ds3 = xr.Dataset({"zed": np.nan})

create a tree from a dictionary of DataTrees and Datasets

In [79]: dt = xr.DataTree.from_dict({"/": dt, "/child-node/new-zed-node": ds3})

We have created a tree with three nodes in it:

In [80]: dt Out[80]: <xarray.DataTree> Group: / │ Dimensions: () │ Data variables: │ foo <U6 24B 'orange' └── Group: /child-node │ Dimensions: (y: 3) │ Coordinates: │ * y (y) int64 24B 0 1 2 │ Data variables: │ bar int64 8B 0 └── Group: /child-node/new-zed-node Dimensions: () Data variables: zed float64 8B nan

Consistency checks are enforced. For instance, if we try to create a cycle, where the root node is also a child of a descendant, the constructor will raise an (InvalidTreeError):

In [81]: dt["child-node"].children = {"new-child": dt} InvalidTreeError: Cannot set parent, as intended parent is already a descendant of this node.

Alternatively you can also create a DataTree object from:

For data files with groups that do not not align seexarray.open_groups() or target each group individuallyxarray.open_dataset(group='groupname'). For more information about coordinate alignment see DataTree Inheritance

DataTree Contents#

Like Dataset, DataTree implements the python mapping interface, but with values given by either DataArray objects or otherDataTree objects.

In [82]: dt["child-node"] Out[82]: <xarray.DataTree 'child-node'> Group: /child-node │ Dimensions: (y: 3) │ Coordinates: │ * y (y) int64 24B 0 1 2 │ Data variables: │ bar int64 8B 0 └── Group: /child-node/new-zed-node Dimensions: () Data variables: zed float64 8B nan

In [83]: dt["foo"] Out[83]: <xarray.DataArray 'foo' ()> Size: 24B array('orange', dtype='<U6')

Iterating over keys will iterate over both the names of variables and child nodes.

We can also access all the data in a single node, and its inherited coordinates, through a dataset-like view

In [84]: dt["child-node"].dataset Out[84]: <xarray.DatasetView> Size: 32B Dimensions: (y: 3) Coordinates:

This demonstrates the fact that the data in any one node is equivalent to the contents of a single Dataset object. The DataTree.dataset property returns an immutable view, but we can instead extract the node’s data contents as a new and mutable Dataset object viaDataTree.to_dataset():

In [85]: dt["child-node"].to_dataset() Out[85]: <xarray.Dataset> Size: 32B Dimensions: (y: 3) Coordinates:

Like with Dataset, you can access the data and coordinate variables of a node separately via the data_vars and coords attributes:

In [86]: dt["child-node"].data_vars Out[86]: Data variables: bar int64 8B 0

In [87]: dt["child-node"].coords Out[87]: Coordinates:

Dictionary-like methods#

We can update a datatree in-place using Python’s standard dictionary syntax, similar to how we can for Dataset objects. For example, to create this example DataTree from scratch, we could have written:

In [88]: dt = xr.DataTree(name="root")

In [89]: dt["foo"] = "orange"

In [90]: dt["child-node"] = xr.DataTree( ....: dataset=xr.Dataset({"bar": 0}, coords={"y": ("y", [0, 1, 2])}) ....: ) ....:

In [91]: dt["child-node/new-zed-node/zed"] = np.nan

In [92]: dt Out[92]: <xarray.DataTree 'root'> Group: / │ Dimensions: () │ Data variables: │ foo <U6 24B 'orange' └── Group: /child-node │ Dimensions: (y: 3) │ Coordinates: │ * y (y) int64 24B 0 1 2 │ Data variables: │ bar int64 8B 0 └── Group: /child-node/new-zed-node Dimensions: () Data variables: zed float64 8B nan

To change the variables in a node of a DataTree, you can use all the standard dictionary methods, including values, items, __delitem__,get and xarray.DataTree.update(). Note that assigning a DataTree object to a DataTree variable using__setitem__ or update() will automatically align the array(s) to the original node’s indexes.

If you copy a DataTree using the copy() function or thexarray.DataTree.copy() method it will copy the subtree, meaning that node and children below it, but no parents above it. Like for Dataset, this copy is shallow by default, but you can copy all the underlying data arrays by calling dt.copy(deep=True).

DataTree Inheritance#

DataTree implements a simple inheritance mechanism. Coordinates, dimensions and their associated indices are propagated from downward starting from the root node to all descendent nodes. Coordinate inheritance was inspired by the NetCDF-CF inherited dimensions, but DataTree’s inheritance is slightly stricter yet easier to reason about.

The constraint that this puts on a DataTree is that dimensions and indices that are inherited must be aligned with any direct descendant node’s existing dimension or index. This allows descendants to use dimensions defined in ancestor nodes, without duplicating that information. But as a consequence, if a dimension-name is defined in on a node and that same dimension-name exists in one of its ancestors, they must align (have the same index and size).

Some examples:

Set up coordinates

In [93]: time = xr.DataArray(data=["2022-01", "2023-01"], dims="time")

In [94]: stations = xr.DataArray(data=list("abcdef"), dims="station")

In [95]: lon = [-100, -80, -60]

In [96]: lat = [10, 20, 30]

Set up fake data

In [97]: wind_speed = xr.DataArray(np.ones((2, 6)) * 2, dims=("time", "station"))

In [98]: pressure = xr.DataArray(np.ones((2, 6)) * 3, dims=("time", "station"))

In [99]: air_temperature = xr.DataArray(np.ones((2, 6)) * 4, dims=("time", "station"))

In [100]: dewpoint = xr.DataArray(np.ones((2, 6)) * 5, dims=("time", "station"))

In [101]: infrared = xr.DataArray(np.ones((2, 3, 3)) * 6, dims=("time", "lon", "lat"))

In [102]: true_color = xr.DataArray(np.ones((2, 3, 3)) * 7, dims=("time", "lon", "lat"))

In [103]: dt2 = xr.DataTree.from_dict( .....: { .....: "/": xr.Dataset( .....: coords={"time": time}, .....: ), .....: "/weather": xr.Dataset( .....: coords={"station": stations}, .....: data_vars={ .....: "wind_speed": wind_speed, .....: "pressure": pressure, .....: }, .....: ), .....: "/weather/temperature": xr.Dataset( .....: data_vars={ .....: "air_temperature": air_temperature, .....: "dewpoint": dewpoint, .....: }, .....: ), .....: "/satellite": xr.Dataset( .....: coords={"lat": lat, "lon": lon}, .....: data_vars={ .....: "infrared": infrared, .....: "true_color": true_color, .....: }, .....: ), .....: }, .....: ) .....:

In [104]: dt2 Out[104]: <xarray.DataTree> Group: / │ Dimensions: (time: 2) │ Coordinates: │ * time (time) <U7 56B '2022-01' '2023-01' ├── Group: /weather │ │ Dimensions: (station: 6, time: 2) │ │ Coordinates: │ │ * station (station) <U1 24B 'a' 'b' 'c' 'd' 'e' 'f' │ │ Data variables: │ │ wind_speed (time, station) float64 96B 2.0 2.0 2.0 2.0 ... 2.0 2.0 2.0 2.0 │ │ pressure (time, station) float64 96B 3.0 3.0 3.0 3.0 ... 3.0 3.0 3.0 3.0 │ └── Group: /weather/temperature │ Dimensions: (time: 2, station: 6) │ Data variables: │ air_temperature (time, station) float64 96B 4.0 4.0 4.0 4.0 ... 4.0 4.0 4.0 │ dewpoint (time, station) float64 96B 5.0 5.0 5.0 5.0 ... 5.0 5.0 5.0 └── Group: /satellite Dimensions: (lat: 3, lon: 3, time: 2) Coordinates: * lat (lat) int64 24B 10 20 30 * lon (lon) int64 24B -100 -80 -60 Data variables: infrared (time, lon, lat) float64 144B 6.0 6.0 6.0 6.0 ... 6.0 6.0 6.0 true_color (time, lon, lat) float64 144B 7.0 7.0 7.0 7.0 ... 7.0 7.0 7.0

Here there are four different coordinate variables, which apply to variables in the DataTree in different ways:

time is a shared coordinate used by both weather and satellite variablesstation is used only for weather variableslat and lon are only use for satellite images

Coordinate variables are inherited to descendent nodes, which is only possible because variables at different levels of a hierarchical DataTree are always aligned. Placing the time variable at the root node automatically indicates that it applies to all descendent nodes. Similarly, station is in the baseweather node, because it applies to all weather variables, both directly inweather and in the temperature sub-tree. Notice the inherited coordinates are explicitly shown in the tree representation under Inherited coordinates:.

In [105]: dt2["/weather"] Out[105]: <xarray.DataTree 'weather'> Group: /weather │ Dimensions: (time: 2, station: 6) │ Coordinates: │ * station (station) <U1 24B 'a' 'b' 'c' 'd' 'e' 'f' │ Inherited coordinates: │ * time (time) <U7 56B '2022-01' '2023-01' │ Data variables: │ wind_speed (time, station) float64 96B 2.0 2.0 2.0 2.0 ... 2.0 2.0 2.0 2.0 │ pressure (time, station) float64 96B 3.0 3.0 3.0 3.0 ... 3.0 3.0 3.0 3.0 └── Group: /weather/temperature Dimensions: (time: 2, station: 6) Data variables: air_temperature (time, station) float64 96B 4.0 4.0 4.0 4.0 ... 4.0 4.0 4.0 dewpoint (time, station) float64 96B 5.0 5.0 5.0 5.0 ... 5.0 5.0 5.0

Accessing any of the lower level trees through the .dataset property automatically includes coordinates from higher levels (e.g., time andstation):

In [106]: dt2["/weather/temperature"].dataset Out[106]: <xarray.DatasetView> Size: 272B Dimensions: (time: 2, station: 6) Coordinates:

Similarly, when you retrieve a Dataset through to_dataset() , the inherited coordinates are included by default unless you exclude them with the inherit flag:

In [107]: dt2["/weather/temperature"].to_dataset() Out[107]: <xarray.Dataset> Size: 272B Dimensions: (time: 2, station: 6) Coordinates:

In [108]: dt2["/weather/temperature"].to_dataset(inherit=False) Out[108]: <xarray.Dataset> Size: 192B Dimensions: (time: 2, station: 6) Dimensions without coordinates: time, station Data variables: air_temperature (time, station) float64 96B 4.0 4.0 4.0 4.0 ... 4.0 4.0 4.0 dewpoint (time, station) float64 96B 5.0 5.0 5.0 5.0 ... 5.0 5.0 5.0

For more examples and further discussion see alignment and coordinate inheritance.

Coordinates#

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

In [109]: ds.coords Out[109]: Coordinates: lat (loc) float64 16B 42.25 42.21 lon (loc) float64 16B -99.83 -99.32

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

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 like syntax, as shown above.

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

In [110]: ds.reset_coords() Out[110]: <xarray.Dataset> Size: 680B Dimensions: (loc: 2, instrument: 3, time: 4) Coordinates:

In [111]: ds.set_coords(["temperature", "precipitation"]) Out[111]: <xarray.Dataset> Size: 680B Dimensions: (loc: 2, instrument: 3, time: 4) Coordinates: temperature (loc, instrument, time) float64 192B 29.11 ... 9.063 precipitation (loc, instrument, time) float64 192B 4.562 ... 1.613 lat (loc) float64 16B 42.25 42.21 lon (loc) float64 16B -99.83 -99.32

In [112]: ds["temperature"].reset_coords(drop=True) Out[112]: <xarray.DataArray 'temperature' (loc: 2, instrument: 3, time: 4)> Size: 192B array([[[29.112, 18.201, 22.83 , 32.927], [29.94 , 7.182, 22.601, 13.789], [14.174, 18.285, 16.152, 26.634]],

   [[21.088, 15.973, 18.551, 17.669],
    [26.953, 13.359, 17.505,  8.167],
    [-5.424, 20.229, 21.915,  9.063]]], shape=(2, 3, 4))

Coordinates:

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

Coordinates methods#

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

In [113]: ds.coords.to_dataset() Out[113]: <xarray.Dataset> Size: 104B Dimensions: (loc: 2, time: 4) Coordinates: lat (loc) float64 16B 42.25 42.21 lon (loc) float64 16B -99.83 -99.32

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

In [114]: alt = xr.Dataset(coords={"z": [10], "lat": 0, "lon": 0})

In [115]: ds.coords.merge(alt.coords) Out[115]: <xarray.Dataset> Size: 80B Dimensions: (time: 4, z: 1) Coordinates:

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

Indexes#

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

In [116]: ds["time"].to_index() Out[116]: DatetimeIndex(['2014-09-06', '2014-09-07', '2014-09-08', '2014-09-09'], 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 each dimension and whose the values are Index objects:

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

MultiIndex coordinates#

Xarray supports labeling coordinate values with a pandas.MultiIndex:

In [118]: midx = pd.MultiIndex.from_arrays( .....: [["R", "R", "V", "V"], [0.1, 0.2, 0.7, 0.9]], names=("band", "wn") .....: ) .....:

In [119]: mda = xr.DataArray(np.random.rand(4), coords={"spec": midx}, dims="spec")

In [120]: mda Out[120]: <xarray.DataArray (spec: 4)> Size: 32B array([0.653, 0.253, 0.466, 0.244]) Coordinates:

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

In [121]: mda["band"] Out[121]: <xarray.DataArray 'band' (spec: 4)> Size: 32B array(['R', 'R', 'V', 'V'], dtype=object) Coordinates:

In [122]: mda.wn Out[122]: <xarray.DataArray 'wn' (spec: 4)> Size: 32B array([0.1, 0.2, 0.7, 0.9]) Coordinates:

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 in the 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 is accessible as a “virtual” coordinate, its name must not conflict with the names of the other levels, coordinates and data variables of the same object. Even though xarray sets default names for multi-indexes with unnamed levels, it is recommended that you explicitly set the names of the levels.