Indexing and selecting data

xarray offers extremely flexible indexing routines that combine the best features of NumPy and pandas for data selection.

The most basic way to access elements of a DataArray object is to use Python’s [] syntax, such as array[i, j], where i and j are both integers. As xarray objects can store coordinates corresponding to each dimension of an array, label-based indexing similar to pandas.DataFrame.loc is also possible. In label-based indexing, the element position i is automatically looked-up from the coordinate values.

Dimensions of xarray objects have names, so you can also lookup the dimensions by name, instead of remembering their positional order.

Thus in total, xarray supports four different kinds of indexing, as described below and summarized in this table:

Dimension lookup Index lookup DataArray syntax Dataset syntax
Positional By integer arr[:, 0] not available
Positional By label arr.loc[:, 'IA'] not available
By name By integer arr.isel(space=0) or
arr[dict(space=0)]
ds.isel(space=0) or
ds[dict(space=0)]
By name By label arr.sel(space='IA') or
arr.loc[dict(space='IA')]
ds.sel(space='IA') or
ds.loc[dict(space='IA')]

More advanced indexing is also possible for all the methods by supplying DataArray objects as indexer. See Vectorized Indexing for the details.

Positional indexing

Indexing a DataArray directly works (mostly) just like it does for numpy arrays, except that the returned object is always another DataArray:

In [1]: arr = xr.DataArray(np.random.rand(4, 3),
   ...:                    [('time', pd.date_range('2000-01-01', periods=4)),
   ...:                     ('space', ['IA', 'IL', 'IN'])])
   ...: 

In [2]: arr[:2]
Out[2]: 
<xarray.DataArray (time: 2, space: 3)>
array([[ 0.12697 ,  0.966718,  0.260476],
       [ 0.897237,  0.37675 ,  0.336222]])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02
  * space    (space) <U2 'IA' 'IL' 'IN'

In [3]: arr[0, 0]
Out[3]: 
<xarray.DataArray ()>
array(0.12696983303810094)
Coordinates:
    time     datetime64[ns] 2000-01-01
    space    <U2 'IA'

In [4]: arr[:, [2, 1]]
Out[4]: 
<xarray.DataArray (time: 4, space: 2)>
array([[ 0.260476,  0.966718],
       [ 0.336222,  0.37675 ],
       [ 0.123102,  0.840255],
       [ 0.447997,  0.373012]])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  * space    (space) <U2 'IN' 'IL'

Attributes are persisted in all indexing operations.

Warning

Positional indexing deviates from the NumPy when indexing with multiple arrays like arr[[0, 1], [0, 1]], as described in Vectorized Indexing.

xarray also supports label-based indexing, just like pandas. Because we use a pandas.Index under the hood, label based indexing is very fast. To do label based indexing, use the loc attribute:

In [5]: arr.loc['2000-01-01':'2000-01-02', 'IA']
Out[5]: 
<xarray.DataArray (time: 2)>
array([ 0.12697 ,  0.897237])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02
    space    <U2 'IA'

In this example, the selected is a subpart of the array in the range ‘2000-01-01’:‘2000-01-02’ along the first coordinate time and with ‘IA’ value from the second coordinate space.

You can perform any of the label indexing operations supported by pandas, including indexing with individual, slices and arrays of labels, as well as indexing with boolean arrays. Like pandas, label based indexing in xarray is inclusive of both the start and stop bounds.

Setting values with label based indexing is also supported:

In [6]: arr.loc['2000-01-01', ['IL', 'IN']] = -10

In [7]: arr
Out[7]: 
<xarray.DataArray (time: 4, space: 3)>
array([[  0.12697 , -10.      , -10.      ],
       [  0.897237,   0.37675 ,   0.336222],
       [  0.451376,   0.840255,   0.123102],
       [  0.543026,   0.373012,   0.447997]])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  * space    (space) <U2 'IA' 'IL' 'IN'

Indexing with dimension names

With the dimension names, we do not have to rely on dimension order and can use them explicitly to slice data. There are two ways to do this:

  1. Use a dictionary as the argument for array positional or label based array indexing:

    # index by integer array indices
    In [8]: arr[dict(space=0, time=slice(None, 2))]
    Out[8]: 
    <xarray.DataArray (time: 2)>
    array([ 0.12697 ,  0.897237])
    Coordinates:
      * time     (time) datetime64[ns] 2000-01-01 2000-01-02
        space    <U2 'IA'
    
    # index by dimension coordinate labels
    In [9]: arr.loc[dict(time=slice('2000-01-01', '2000-01-02'))]
    Out[9]: 
    <xarray.DataArray (time: 2, space: 3)>
    array([[  0.12697 , -10.      , -10.      ],
           [  0.897237,   0.37675 ,   0.336222]])
    Coordinates:
      * time     (time) datetime64[ns] 2000-01-01 2000-01-02
      * space    (space) <U2 'IA' 'IL' 'IN'
    
  2. Use the sel() and isel() convenience methods:

    # index by integer array indices
    In [10]: arr.isel(space=0, time=slice(None, 2))
    Out[10]: 
    <xarray.DataArray (time: 2)>
    array([ 0.12697 ,  0.897237])
    Coordinates:
      * time     (time) datetime64[ns] 2000-01-01 2000-01-02
        space    <U2 'IA'
    
    # index by dimension coordinate labels
    In [11]: arr.sel(time=slice('2000-01-01', '2000-01-02'))
    Out[11]: 
    <xarray.DataArray (time: 2, space: 3)>
    array([[  0.12697 , -10.      , -10.      ],
           [  0.897237,   0.37675 ,   0.336222]])
    Coordinates:
      * time     (time) datetime64[ns] 2000-01-01 2000-01-02
      * space    (space) <U2 'IA' 'IL' 'IN'
    

The arguments to these methods can be any objects that could index the array along the dimension given by the keyword, e.g., labels for an individual value, Python slice() objects or 1-dimensional arrays.

Note

We would love to be able to do indexing with labeled dimension names inside brackets, but unfortunately, Python does yet not support indexing with keyword arguments like arr[space=0]

Nearest neighbor lookups

The label based selection methods sel(), reindex() and reindex_like() all support method and tolerance keyword argument. The method parameter allows for enabling nearest neighbor (inexact) lookups by use of the methods 'pad', 'backfill' or 'nearest':

In [12]: data = xr.DataArray([1, 2, 3], [('x', [0, 1, 2])])

In [13]: data.sel(x=[1.1, 1.9], method='nearest')
Out[13]: 
<xarray.DataArray (x: 2)>
array([2, 3])
Coordinates:
  * x        (x) int64 1 2

In [14]: data.sel(x=0.1, method='backfill')
Out[14]: 
<xarray.DataArray ()>
array(2)
Coordinates:
    x        int64 1

In [15]: data.reindex(x=[0.5, 1, 1.5, 2, 2.5], method='pad')
Out[15]: 
<xarray.DataArray (x: 5)>
array([1, 2, 2, 3, 3])
Coordinates:
  * x        (x) float64 0.5 1.0 1.5 2.0 2.5

Tolerance limits the maximum distance for valid matches with an inexact lookup:

In [16]: data.reindex(x=[1.1, 1.5], method='nearest', tolerance=0.2)
Out[16]: 
<xarray.DataArray (x: 2)>
array([  2.,  nan])
Coordinates:
  * x        (x) float64 1.1 1.5

The method parameter is not yet supported if any of the arguments to .sel() is a slice object:

In [17]: data.sel(x=slice(1, 3), method='nearest')
NotImplementedError

However, you don’t need to use method to do inexact slicing. Slicing already returns all values inside the range (inclusive), as long as the index labels are monotonic increasing:

In [18]: data.sel(x=slice(0.9, 3.1))
Out[18]: 
<xarray.DataArray (x: 2)>
array([2, 3])
Coordinates:
  * x        (x) int64 1 2

Indexing axes with monotonic decreasing labels also works, as long as the slice or .loc arguments are also decreasing:

In [19]: reversed_data = data[::-1]

In [20]: reversed_data.loc[3.1:0.9]
Out[20]: 
<xarray.DataArray (x: 2)>
array([3, 2])
Coordinates:
  * x        (x) int64 2 1

Dataset indexing

We can also use these methods to index all variables in a dataset simultaneously, returning a new dataset:

In [21]: ds = arr.to_dataset(name='foo')

In [22]: ds.isel(space=[0], time=[0])
Out[22]: 
<xarray.Dataset>
Dimensions:  (space: 1, time: 1)
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01
  * space    (space) <U2 'IA'
Data variables:
    foo      (time, space) float64 0.127

In [23]: ds.sel(time='2000-01-01')
Out[23]: 
<xarray.Dataset>
Dimensions:  (space: 3)
Coordinates:
    time     datetime64[ns] 2000-01-01
  * space    (space) <U2 'IA' 'IL' 'IN'
Data variables:
    foo      (space) float64 0.127 -10.0 -10.0

Positional indexing on a dataset is not supported because the ordering of dimensions in a dataset is somewhat ambiguous (it can vary between different arrays). However, you can do normal indexing with dimension names:

In [24]: ds[dict(space=[0], time=[0])]
Out[24]: 
<xarray.Dataset>
Dimensions:  (space: 1, time: 1)
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01
  * space    (space) <U2 'IA'
Data variables:
    foo      (time, space) float64 0.127

In [25]: ds.loc[dict(time='2000-01-01')]
Out[25]: 
<xarray.Dataset>
Dimensions:  (space: 3)
Coordinates:
    time     datetime64[ns] 2000-01-01
  * space    (space) <U2 'IA' 'IL' 'IN'
Data variables:
    foo      (space) float64 0.127 -10.0 -10.0

Using indexing to assign values to a subset of dataset (e.g., ds[dict(space=0)] = 1) is not yet supported.

Dropping labels

The drop() method returns a new object with the listed index labels along a dimension dropped:

In [26]: ds.drop(['IN', 'IL'], dim='space')
Out[26]: 
<xarray.Dataset>
Dimensions:  (space: 1, time: 4)
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  * space    (space) <U2 'IA'
Data variables:
    foo      (time, space) float64 0.127 0.8972 0.4514 0.543

drop is both a Dataset and DataArray method.

Masking with where

Indexing methods on xarray objects generally return a subset of the original data. However, it is sometimes useful to select an object with the same shape as the original data, but with some elements masked. To do this type of selection in xarray, use where():

In [27]: arr2 = xr.DataArray(np.arange(16).reshape(4, 4), dims=['x', 'y'])

In [28]: arr2.where(arr2.x + arr2.y < 4)
Out[28]: 
<xarray.DataArray (x: 4, y: 4)>
array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,  nan],
       [  8.,   9.,  nan,  nan],
       [ 12.,  nan,  nan,  nan]])
Dimensions without coordinates: x, y

This is particularly useful for ragged indexing of multi-dimensional data, e.g., to apply a 2D mask to an image. Note that where follows all the usual xarray broadcasting and alignment rules for binary operations (e.g., +) between the object being indexed and the condition, as described in Computation:

In [29]: arr2.where(arr2.y < 2)
Out[29]: 
<xarray.DataArray (x: 4, y: 4)>
array([[  0.,   1.,  nan,  nan],
       [  4.,   5.,  nan,  nan],
       [  8.,   9.,  nan,  nan],
       [ 12.,  13.,  nan,  nan]])
Dimensions without coordinates: x, y

By default where maintains the original size of the data. For cases where the selected data size is much smaller than the original data, use of the option drop=True clips coordinate elements that are fully masked:

In [30]: arr2.where(arr2.y < 2, drop=True)
Out[30]: 
<xarray.DataArray (x: 4, y: 2)>
array([[  0.,   1.],
       [  4.,   5.],
       [  8.,   9.],
       [ 12.,  13.]])
Dimensions without coordinates: x, y

Selecting values with isin

To check whether elements of an xarray object contain a single object, you can compare with the equality operator == (e.g., arr == 3). To check multiple values, use isin():

In [31]: arr = xr.DataArray([1, 2, 3, 4, 5], dims=['x'])

In [32]: arr.isin([2, 4])
Out[32]: 
<xarray.DataArray (x: 5)>
array([False,  True, False,  True, False], dtype=bool)
Dimensions without coordinates: x

isin() works particularly well with where() to support indexing by arrays that are not already labels of an array:

In [33]: lookup = xr.DataArray([-1, -2, -3, -4, -5], dims=['x'])

In [34]: arr.where(lookup.isin([-2, -4]), drop=True)
Out[34]: 
<xarray.DataArray (x: 2)>
array([ 2.,  4.])
Dimensions without coordinates: x

However, some caution is in order: when done repeatedly, this type of indexing is significantly slower than using sel().

Vectorized Indexing

Like numpy and pandas, xarray supports indexing many array elements at once in a vectorized manner.

If you only provide integers, slices, or unlabeled arrays (array without dimension names, such as np.ndarray, list, but not DataArray() or Variable()) indexing can be understood as orthogonally. Each indexer component selects independently along the corresponding dimension, similar to how vector indexing works in Fortran or MATLAB, or after using the numpy.ix_() helper:

In [35]: da = xr.DataArray(np.arange(12).reshape((3, 4)), dims=['x', 'y'],
   ....:                   coords={'x': [0, 1, 2], 'y': ['a', 'b', 'c', 'd']})
   ....: 

In [36]: da
Out[36]: 
<xarray.DataArray (x: 3, y: 4)>
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
Coordinates:
  * x        (x) int64 0 1 2
  * y        (y) <U1 'a' 'b' 'c' 'd'

In [37]: da[[0, 1], [1, 1]]
Out[37]: 
<xarray.DataArray (x: 2, y: 2)>
array([[1, 1],
       [5, 5]])
Coordinates:
  * x        (x) int64 0 1
  * y        (y) <U1 'b' 'b'

For more flexibility, you can supply DataArray() objects as indexers. Dimensions on resultant arrays are given by the ordered union of the indexers’ dimensions:

In [38]: ind_x = xr.DataArray([0, 1], dims=['x'])

In [39]: ind_y = xr.DataArray([0, 1], dims=['y'])

In [40]: da[ind_x, ind_y]  # orthogonal indexing
Out[40]: 
<xarray.DataArray (x: 2, y: 2)>
array([[0, 1],
       [4, 5]])
Coordinates:
  * x        (x) int64 0 1
  * y        (y) <U1 'a' 'b'

In [41]: da[ind_x, ind_x]  # vectorized indexing
Out[41]: 
<xarray.DataArray (x: 2)>
array([0, 5])
Coordinates:
  * x        (x) int64 0 1
    y        (x) <U1 'a' 'b'

Slices or sequences/arrays without named-dimensions are treated as if they have the same dimension which is indexed along:

# Because [0, 1] is used to index along dimension 'x',
# it is assumed to have dimension 'x'
In [42]: da[[0, 1], ind_x]
Out[42]: 
<xarray.DataArray (x: 2)>
array([0, 5])
Coordinates:
  * x        (x) int64 0 1
    y        (x) <U1 'a' 'b'

Furthermore, you can use multi-dimensional DataArray() as indexers, where the resultant array dimension is also determined by indexers’ dimension:

In [43]: ind = xr.DataArray([[0, 1], [0, 1]], dims=['a', 'b'])

In [44]: da[ind]
Out[44]: 
<xarray.DataArray (a: 2, b: 2, y: 4)>
array([[[0, 1, 2, 3],
        [4, 5, 6, 7]],

       [[0, 1, 2, 3],
        [4, 5, 6, 7]]])
Coordinates:
    x        (a, b) int64 0 1 0 1
  * y        (y) <U1 'a' 'b' 'c' 'd'
Dimensions without coordinates: a, b

Similar to how NumPy’s advanced indexing works, vectorized indexing for xarray is based on our broadcasting rules. See Indexing rules for the complete specification.

Vectorized indexing also works with isel, loc, and sel:

In [45]: ind = xr.DataArray([[0, 1], [0, 1]], dims=['a', 'b'])

In [46]: da.isel(y=ind)  # same as da[:, ind]
Out[46]: 
<xarray.DataArray (x: 3, a: 2, b: 2)>
array([[[0, 1],
        [0, 1]],

       [[4, 5],
        [4, 5]],

       [[8, 9],
        [8, 9]]])
Coordinates:
  * x        (x) int64 0 1 2
    y        (a, b) object 'a' 'b' 'a' 'b'
Dimensions without coordinates: a, b

In [47]: ind = xr.DataArray([['a', 'b'], ['b', 'a']], dims=['a', 'b'])

In [48]: da.loc[:, ind]  # same as da.sel(y=ind)
Out[48]: 
<xarray.DataArray (x: 3, a: 2, b: 2)>
array([[[0, 1],
        [1, 0]],

       [[4, 5],
        [5, 4]],

       [[8, 9],
        [9, 8]]])
Coordinates:
  * x        (x) int64 0 1 2
    y        (a, b) object 'a' 'b' 'b' 'a'
Dimensions without coordinates: a, b

These methods may and also be applied to Dataset objects

In [49]: ds2 = da.to_dataset(name='bar')

In [50]: ds2.isel(x=xr.DataArray([0, 1, 2], dims=['points']))
Out[50]: 
<xarray.Dataset>
Dimensions:  (points: 3, y: 4)
Coordinates:
    x        (points) int64 0 1 2
  * y        (y) <U1 'a' 'b' 'c' 'd'
Dimensions without coordinates: points
Data variables:
    bar      (points, y) int64 0 1 2 3 4 5 6 7 8 9 10 11

Tip

If you are lazily loading your data from disk, not every form of vectorized indexing is supported (or if supported, may not be supported efficiently). You may find increased performance by loading your data into memory first, e.g., with load().

Note

Vectorized indexing is a new feature in v0.10. In older versions of xarray, dimensions of indexers are ignored. Dedicated methods for some advanced indexing use cases, isel_points and sel_points are now deprecated. See More advanced indexing for their alternative.

Note

If an indexer is a DataArray(), its coordinates should not conflict with the selected subpart of the target array (except for the explicitly indexed dimensions with .loc/.sel). Otherwise, IndexError will be raised.

Assigning values with indexing

Vectorized indexing can be used to assign values to xarray object.

In [51]: da = xr.DataArray(np.arange(12).reshape((3, 4)), dims=['x', 'y'],
   ....:                   coords={'x': [0, 1, 2], 'y': ['a', 'b', 'c', 'd']})
   ....: 

In [52]: da
Out[52]: 
<xarray.DataArray (x: 3, y: 4)>
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
Coordinates:
  * x        (x) int64 0 1 2
  * y        (y) <U1 'a' 'b' 'c' 'd'

In [53]: da[0] = -1  # assignment with broadcasting

In [54]: da
Out[54]: 
<xarray.DataArray (x: 3, y: 4)>
array([[-1, -1, -1, -1],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
Coordinates:
  * x        (x) int64 0 1 2
  * y        (y) <U1 'a' 'b' 'c' 'd'

In [55]: ind_x = xr.DataArray([0, 1], dims=['x'])

In [56]: ind_y = xr.DataArray([0, 1], dims=['y'])

In [57]: da[ind_x, ind_y] = -2  # assign -2 to (ix, iy) = (0, 0) and (1, 1)

In [58]: da
Out[58]: 
<xarray.DataArray (x: 3, y: 4)>
array([[-2, -2, -1, -1],
       [-2, -2,  6,  7],
       [ 8,  9, 10, 11]])
Coordinates:
  * x        (x) int64 0 1 2
  * y        (y) <U1 'a' 'b' 'c' 'd'

In [59]: da[ind_x, ind_y] += 100  # increment is also possible

In [60]: da
Out[60]: 
<xarray.DataArray (x: 3, y: 4)>
array([[98, 98, -1, -1],
       [98, 98,  6,  7],
       [ 8,  9, 10, 11]])
Coordinates:
  * x        (x) int64 0 1 2
  * y        (y) <U1 'a' 'b' 'c' 'd'

Like numpy.ndarray, value assignment sometimes works differently from what one may expect.

In [61]: da = xr.DataArray([0, 1, 2, 3], dims=['x'])

In [62]: ind = xr.DataArray([0, 0, 0], dims=['x'])

In [63]: da[ind] -= 1

In [64]: da
Out[64]: 
<xarray.DataArray (x: 4)>
array([-1,  1,  2,  3])
Dimensions without coordinates: x

Where the 0th element will be subtracted 1 only once. This is because v[0] = v[0] - 1 is called three times, rather than v[0] = v[0] - 1 - 1 - 1. See Assigning values to indexed arrays for the details.

Note

Dask array does not support value assignment (see Parallel computing with dask for the details).

Note

Coordinates in both the left- and right-hand-side arrays should not conflict with each other. Otherwise, IndexError will be raised.

Warning

Do not try to assign values when using any of the indexing methods isel or sel:

# DO NOT do this
arr.isel(space=0) = 0

Assigning values with the chained indexing using .sel or .isel fails silently.

In [65]: da = xr.DataArray([0, 1, 2, 3], dims=['x'])

# DO NOT do this
In [66]: da.isel(x=[0, 1, 2])[1] = -1

In [67]: da
Out[67]: 
<xarray.DataArray (x: 4)>
array([0, 1, 2, 3])
Dimensions without coordinates: x

More advanced indexing

The use of DataArray() objects as indexers enables very flexible indexing. The following is an example of the pointwise indexing:

In [68]: da = xr.DataArray(np.arange(56).reshape((7, 8)), dims=['x', 'y'])

In [69]: da
Out[69]: 
<xarray.DataArray (x: 7, y: 8)>
array([[ 0,  1,  2,  3,  4,  5,  6,  7],
       [ 8,  9, 10, 11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29, 30, 31],
       [32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47],
       [48, 49, 50, 51, 52, 53, 54, 55]])
Dimensions without coordinates: x, y

In [70]: da.isel(x=xr.DataArray([0, 1, 6], dims='z'),
   ....:         y=xr.DataArray([0, 1, 0], dims='z'))
   ....: 
Out[70]: 
<xarray.DataArray (z: 3)>
array([ 0,  9, 48])
Dimensions without coordinates: z

where three elements at (ix, iy) = ((0, 0), (1, 1), (6, 0)) are selected and mapped along a new dimension z.

If you want to add a coordinate to the new dimension z, you can supply a DataArray() with a coordinate,

In [71]: da.isel(x=xr.DataArray([0, 1, 6], dims='z',
   ....:                        coords={'z': ['a', 'b', 'c']}),
   ....:         y=xr.DataArray([0, 1, 0], dims='z'))
   ....: 
Out[71]: 
<xarray.DataArray (z: 3)>
array([ 0,  9, 48])
Coordinates:
  * z        (z) <U1 'a' 'b' 'c'

Analogously, label-based pointwise-indexing is also possible by the .sel method:

In [72]: times = xr.DataArray(pd.to_datetime(['2000-01-03', '2000-01-02', '2000-01-01']),
   ....:                      dims='new_time')
   ....: 

In [73]: arr.sel(space=xr.DataArray(['IA', 'IL', 'IN'], dims=['new_time']),
   ....:         time=times)
   ....: 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-73-012885a177c1> in <module>()
      1 arr.sel(space=xr.DataArray(['IA', 'IL', 'IN'], dims=['new_time']),
----> 2         time=times)
      3 

~/checkouts/readthedocs.org/user_builds/xray/conda/v0.10.3/lib/python3.6/site-packages/xarray-0.10.3-py3.6.egg/xarray/core/dataarray.py in sel(self, method, tolerance, drop, **indexers)
    765         """
    766         ds = self._to_temp_dataset().sel(drop=drop, method=method,
--> 767                                          tolerance=tolerance, **indexers)
    768         return self._from_temp_dataset(ds)
    769 

~/checkouts/readthedocs.org/user_builds/xray/conda/v0.10.3/lib/python3.6/site-packages/xarray-0.10.3-py3.6.egg/xarray/core/dataset.py in sel(self, method, tolerance, drop, **indexers)
   1470         """
   1471         pos_indexers, new_indexes = remap_label_indexers(self, method,
-> 1472                                                          tolerance, **indexers)
   1473         result = self.isel(drop=drop, **pos_indexers)
   1474         return result._replace_indexes(new_indexes)

~/checkouts/readthedocs.org/user_builds/xray/conda/v0.10.3/lib/python3.6/site-packages/xarray-0.10.3-py3.6.egg/xarray/core/coordinates.py in remap_label_indexers(obj, method, tolerance, **indexers)
    344 
    345     pos_indexers, new_indexes = indexing.remap_label_indexers(
--> 346         obj, v_indexers, method=method, tolerance=tolerance
    347     )
    348     # attach indexer's coordinate to pos_indexers

~/checkouts/readthedocs.org/user_builds/xray/conda/v0.10.3/lib/python3.6/site-packages/xarray-0.10.3-py3.6.egg/xarray/core/indexing.py in remap_label_indexers(data_obj, indexers, method, tolerance)
    235     new_indexes = {}
    236 
--> 237     dim_indexers = get_dim_indexers(data_obj, indexers)
    238     for dim, label in iteritems(dim_indexers):
    239         try:

~/checkouts/readthedocs.org/user_builds/xray/conda/v0.10.3/lib/python3.6/site-packages/xarray-0.10.3-py3.6.egg/xarray/core/indexing.py in get_dim_indexers(data_obj, indexers)
    203     if invalid:
    204         raise ValueError("dimensions or multi-index levels %r do not exist"
--> 205                          % invalid)
    206 
    207     level_indexers = defaultdict(dict)

ValueError: dimensions or multi-index levels ['space', 'time'] do not exist

Align and reindex

xarray’s reindex, reindex_like and align impose a DataArray or Dataset onto a new set of coordinates corresponding to dimensions. The original values are subset to the index labels still found in the new labels, and values corresponding to new labels not found in the original object are in-filled with NaN.

xarray operations that combine multiple objects generally automatically align their arguments to share the same indexes. However, manual alignment can be useful for greater control and for increased performance.

To reindex a particular dimension, use reindex():

In [74]: arr.reindex(space=['IA', 'CA'])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-74-7487217e63b1> in <module>()
----> 1 arr.reindex(space=['IA', 'CA'])

~/checkouts/readthedocs.org/user_builds/xray/conda/v0.10.3/lib/python3.6/site-packages/xarray-0.10.3-py3.6.egg/xarray/core/dataarray.py in reindex(self, method, tolerance, copy, **indexers)
    880         """
    881         ds = self._to_temp_dataset().reindex(
--> 882             method=method, tolerance=tolerance, copy=copy, **indexers)
    883         return self._from_temp_dataset(ds)
    884 

~/checkouts/readthedocs.org/user_builds/xray/conda/v0.10.3/lib/python3.6/site-packages/xarray-0.10.3-py3.6.egg/xarray/core/dataset.py in reindex(self, indexers, method, tolerance, copy, **kw_indexers)
   1767         bad_dims = [d for d in indexers if d not in self.dims]
   1768         if bad_dims:
-> 1769             raise ValueError('invalid reindex dimensions: %s' % bad_dims)
   1770 
   1771         variables = alignment.reindex_variables(

ValueError: invalid reindex dimensions: ['space']

The reindex_like() method is a useful shortcut. To demonstrate, we will make a subset DataArray with new values:

In [75]: foo = arr.rename('foo')

In [76]: baz = (10 * arr[:2, :2]).rename('baz')
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-76-111d5d54c6b0> in <module>()
----> 1 baz = (10 * arr[:2, :2]).rename('baz')

~/checkouts/readthedocs.org/user_builds/xray/conda/v0.10.3/lib/python3.6/site-packages/xarray-0.10.3-py3.6.egg/xarray/core/dataarray.py in __getitem__(self, key)
    471         else:
    472             # xarray-style array indexing
--> 473             return self.isel(**self._item_key_to_dict(key))
    474 
    475     def __setitem__(self, key, value):

~/checkouts/readthedocs.org/user_builds/xray/conda/v0.10.3/lib/python3.6/site-packages/xarray-0.10.3-py3.6.egg/xarray/core/dataarray.py in _item_key_to_dict(self, key)
    437             return key
    438         else:
--> 439             key = indexing.expanded_indexer(key, self.ndim)
    440             return dict(zip(self.dims, key))
    441 

~/checkouts/readthedocs.org/user_builds/xray/conda/v0.10.3/lib/python3.6/site-packages/xarray-0.10.3-py3.6.egg/xarray/core/indexing.py in expanded_indexer(key, ndim)
     40             new_key.append(k)
     41     if len(new_key) > ndim:
---> 42         raise IndexError('too many indices')
     43     new_key.extend((ndim - len(new_key)) * [slice(None)])
     44     return tuple(new_key)

IndexError: too many indices

In [77]: baz
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-77-6eadeac2dade> in <module>()
----> 1 baz

NameError: name 'baz' is not defined

Reindexing foo with baz selects out the first two values along each dimension:

In [78]: foo.reindex_like(baz)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-78-7cbddb96db16> in <module>()
----> 1 foo.reindex_like(baz)

NameError: name 'baz' is not defined

The opposite operation asks us to reindex to a larger shape, so we fill in the missing values with NaN:

In [79]: baz.reindex_like(foo)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-79-1948f3ca3545> in <module>()
----> 1 baz.reindex_like(foo)

NameError: name 'baz' is not defined

The align() function lets us perform more flexible database-like 'inner', 'outer', 'left' and 'right' joins:

In [80]: xr.align(foo, baz, join='inner')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-80-9db9be39fbf6> in <module>()
----> 1 xr.align(foo, baz, join='inner')

NameError: name 'baz' is not defined

In [81]: xr.align(foo, baz, join='outer')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-81-37f3bf3c6366> in <module>()
----> 1 xr.align(foo, baz, join='outer')

NameError: name 'baz' is not defined

Both reindex_like and align work interchangeably between DataArray and Dataset objects, and with any number of matching dimension names:

In [82]: ds
Out[82]: 
<xarray.Dataset>
Dimensions:  (space: 3, time: 4)
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  * space    (space) <U2 'IA' 'IL' 'IN'
Data variables:
    foo      (time, space) float64 0.127 -10.0 -10.0 0.8972 0.3767 0.3362 ...

In [83]: ds.reindex_like(baz)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-83-0d971433d0be> in <module>()
----> 1 ds.reindex_like(baz)

NameError: name 'baz' is not defined

In [84]: other = xr.DataArray(['a', 'b', 'c'], dims='other')

# this is a no-op, because there are no shared dimension names
In [85]: ds.reindex_like(other)
Out[85]: 
<xarray.Dataset>
Dimensions:  (space: 3, time: 4)
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  * space    (space) <U2 'IA' 'IL' 'IN'
Data variables:
    foo      (time, space) float64 0.127 -10.0 -10.0 0.8972 0.3767 0.3362 ...

Missing coordinate labels

Coordinate labels for each dimension are optional (as of xarray v0.9). Label based indexing with .sel and .loc uses standard positional, integer-based indexing as a fallback for dimensions without a coordinate label:

In [86]: array = xr.DataArray([1, 2, 3], dims='x')

In [87]: array.sel(x=[0, -1])
Out[87]: 
<xarray.DataArray (x: 2)>
array([1, 3])
Dimensions without coordinates: x

Alignment between xarray objects where one or both do not have coordinate labels succeeds only if all dimensions of the same name have the same length. Otherwise, it raises an informative error:

In [88]: xr.align(array, array[:2])
ValueError: arguments without labels along dimension 'x' cannot be aligned because they have different dimension sizes: {2, 3}

Underlying Indexes

xarray uses the pandas.Index internally to perform indexing operations. If you need to access the underlying indexes, they are available through the indexes attribute.

In [89]: arr
Out[89]: 
<xarray.DataArray (x: 5)>
array([1, 2, 3, 4, 5])
Dimensions without coordinates: x

In [90]: arr.indexes
Out[90]: 

In [91]: arr.indexes['time']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-91-1d2af65d4da4> in <module>()
----> 1 arr.indexes['time']

~/checkouts/readthedocs.org/user_builds/xray/conda/v0.10.3/lib/python3.6/site-packages/xarray-0.10.3-py3.6.egg/xarray/core/coordinates.py in __getitem__(self, key)
    302     def __getitem__(self, key):
    303         if key not in self._sizes:
--> 304             raise KeyError(key)
    305         return self._variables[key].to_index()
    306 

KeyError: 'time'

Use get_index() to get an index for a dimension, falling back to a default pandas.RangeIndex if it has no coordinate labels:

In [92]: array
Out[92]: 
<xarray.DataArray (x: 3)>
array([1, 2, 3])
Dimensions without coordinates: x

In [93]: array.get_index('x')
Out[93]: RangeIndex(start=0, stop=3, step=1, name='x')

Copies vs. Views

Whether array indexing returns a view or a copy of the underlying data depends on the nature of the labels.

For positional (integer) indexing, xarray follows the same rules as NumPy:

  • Positional indexing with only integers and slices returns a view.
  • Positional indexing with arrays or lists returns a copy.

The rules for label based indexing are more complex:

  • Label-based indexing with only slices returns a view.
  • Label-based indexing with arrays returns a copy.
  • Label-based indexing with scalars returns a view or a copy, depending upon if the corresponding positional indexer can be represented as an integer or a slice object. The exact rules are determined by pandas.

Whether data is a copy or a view is more predictable in xarray than in pandas, so unlike pandas, xarray does not produce SettingWithCopy warnings. However, you should still avoid assignment with chained indexing.

Multi-level indexing

Just like pandas, advanced indexing on multi-level indexes is possible with loc and sel. You can slice a multi-index by providing multiple indexers, i.e., a tuple of slices, labels, list of labels, or any selector allowed by pandas:

In [94]: midx = pd.MultiIndex.from_product([list('abc'), [0, 1]],
   ....:                                   names=('one', 'two'))
   ....: 

In [95]: mda = xr.DataArray(np.random.rand(6, 3),
   ....:                    [('x', midx), ('y', range(3))])
   ....: 

In [96]: mda
Out[96]: 
<xarray.DataArray (x: 6, y: 3)>
array([[ 0.129441,  0.859879,  0.820388],
       [ 0.352054,  0.228887,  0.776784],
       [ 0.594784,  0.137554,  0.8529  ],
       [ 0.235507,  0.146227,  0.589869],
       [ 0.574012,  0.06127 ,  0.590426],
       [ 0.24535 ,  0.340445,  0.984729]])
Coordinates:
  * x        (x) MultiIndex
  - one      (x) object 'a' 'a' 'b' 'b' 'c' 'c'
  - two      (x) int64 0 1 0 1 0 1
  * y        (y) int64 0 1 2

In [97]: mda.sel(x=(list('ab'), [0]))
Out[97]: 
<xarray.DataArray (x: 2, y: 3)>
array([[ 0.129441,  0.859879,  0.820388],
       [ 0.594784,  0.137554,  0.8529  ]])
Coordinates:
  * x        (x) MultiIndex
  - one      (x) object 'a' 'b'
  - two      (x) int64 0 0
  * y        (y) int64 0 1 2

You can also select multiple elements by providing a list of labels or tuples or a slice of tuples:

In [98]: mda.sel(x=[('a', 0), ('b', 1)])
Out[98]: 
<xarray.DataArray (x: 2, y: 3)>
array([[ 0.129441,  0.859879,  0.820388],
       [ 0.235507,  0.146227,  0.589869]])
Coordinates:
  * x        (x) MultiIndex
  - one      (x) object 'a' 'b'
  - two      (x) int64 0 1
  * y        (y) int64 0 1 2

Additionally, xarray supports dictionaries:

In [99]: mda.sel(x={'one': 'a', 'two': 0})
Out[99]: 
<xarray.DataArray (y: 3)>
array([ 0.129441,  0.859879,  0.820388])
Coordinates:
    x        object ('a', 0)
  * y        (y) int64 0 1 2

For convenience, sel also accepts multi-index levels directly as keyword arguments:

In [100]: mda.sel(one='a', two=0)
Out[100]: 
<xarray.DataArray (y: 3)>
array([ 0.129441,  0.859879,  0.820388])
Coordinates:
    x        object ('a', 0)
  * y        (y) int64 0 1 2

Note that using sel it is not possible to mix a dimension indexer with level indexers for that dimension (e.g., mda.sel(x={'one': 'a'}, two=0) will raise a ValueError).

Like pandas, xarray handles partial selection on multi-index (level drop). As shown below, it also renames the dimension / coordinate when the multi-index is reduced to a single index.

In [101]: mda.loc[{'one': 'a'}, ...]
Out[101]: 
<xarray.DataArray (two: 2, y: 3)>
array([[ 0.129441,  0.859879,  0.820388],
       [ 0.352054,  0.228887,  0.776784]])
Coordinates:
  * two      (two) int64 0 1
  * y        (y) int64 0 1 2

Unlike pandas, xarray does not guess whether you provide index levels or dimensions when using loc in some ambiguous cases. For example, for mda.loc[{'one': 'a', 'two': 0}] and mda.loc['a', 0] xarray always interprets (‘one’, ‘two’) and (‘a’, 0) as the names and labels of the 1st and 2nd dimension, respectively. You must specify all dimensions or use the ellipsis in the loc specifier, e.g. in the example above, mda.loc[{'one': 'a', 'two': 0}, :] or mda.loc[('a', 0), ...].

Indexing rules

Here we describe the full rules xarray uses for vectorized indexing. Note that this is for the purposes of explanation: for the sake of efficiency and to support various backends, the actual implementation is different.

  1. (Only for label based indexing.) Look up positional indexes along each dimension from the corresponding pandas.Index.
  2. A full slice object : is inserted for each dimension without an indexer.
  3. slice objects are converted into arrays, given by np.arange(*slice.indices(...)).
  4. Assume dimension names for array indexers without dimensions, such as np.ndarray and list, from the dimensions to be indexed along. For example, v.isel(x=[0, 1]) is understood as v.isel(x=xr.DataArray([0, 1], dims=['x'])).
  5. For each variable in a Dataset or DataArray (the array and its coordinates):
    1. Broadcast all relevant indexers based on their dimension names (see Broadcasting by dimension name for full details).
    2. Index the underling array by the broadcast indexers, using NumPy’s advanced indexing rules.
  6. If any indexer DataArray has coordinates and no coordinate with the same name exists, attach them to the indexed object.

Note

Only 1-dimensional boolean arrays can be used as indexers.