Indexing and selecting data

Similarly to pandas objects, xray objects support both integer and label based lookups along each dimension. However, xray objects also have named dimensions, so you can optionally use dimension names instead of relying on the positional ordering of dimensions.

Thus in total, xray 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')]

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 = xray.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]: 
<xray.DataArray (time: 2, space: 3)>
array([[ 0.127,  0.967,  0.26 ],
       [ 0.897,  0.377,  0.336]])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02
  * space    (space) |S2 'IA' 'IL' 'IN'

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

In [4]: arr[:, [2, 1]]
Out[4]: 
<xray.DataArray (time: 4, space: 2)>
array([[ 0.26 ,  0.967],
       [ 0.336,  0.377],
       [ 0.123,  0.84 ],
       [ 0.448,  0.373]])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  * space    (space) |S2 '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 Orthogonal (outer) vs. vectorized indexing. See Pointwise indexing for how to achieve this functionality in xray.

xray 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]: 
<xray.DataArray (time: 2)>
array([ 0.127,  0.897])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02
    space    |S2 'IA'

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 xray 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]: 
<xray.DataArray (time: 4, space: 3)>
array([[  0.127, -10.   , -10.   ],
       [  0.897,   0.377,   0.336],
       [  0.451,   0.84 ,   0.123],
       [  0.543,   0.373,   0.448]])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  * space    (space) |S2 'IA' 'IL' 'IN'

Indexing with labeled dimensions

With labeled dimensions, 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]: 
    <xray.DataArray (time: 2)>
    array([ 0.127,  0.897])
    Coordinates:
      * time     (time) datetime64[ns] 2000-01-01 2000-01-02
        space    |S2 'IA'
    
    # index by dimension coordinate labels
    In [9]: arr.loc[dict(time=slice('2000-01-01', '2000-01-02'))]
    Out[9]: 
    <xray.DataArray (time: 2, space: 3)>
    array([[  0.127, -10.   , -10.   ],
           [  0.897,   0.377,   0.336]])
    Coordinates:
      * time     (time) datetime64[ns] 2000-01-01 2000-01-02
      * space    (space) |S2 '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]: 
    <xray.DataArray (time: 2)>
    array([ 0.127,  0.897])
    Coordinates:
      * time     (time) datetime64[ns] 2000-01-01 2000-01-02
        space    |S2 'IA'
    
    # index by dimension coordinate labels
    In [11]: arr.sel(time=slice('2000-01-01', '2000-01-02'))
    Out[11]: 
    <xray.DataArray (time: 2, space: 3)>
    array([[  0.127, -10.   , -10.   ],
           [  0.897,   0.377,   0.336]])
    Coordinates:
      * time     (time) datetime64[ns] 2000-01-01 2000-01-02
      * space    (space) |S2 '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]

Warning

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

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

Depending on whether the underlying numpy indexing returns a copy or a view, the method will fail, and when it fails, it will fail silently. Instead, you should use normal index assignment:

# this is safe
arr[dict(space=0)] = 0

Pointwise indexing

xray pointwise indexing supports the indexing along multiple labeled dimensions using list-like objects. While isel() performs orthogonal indexing, the isel_points() method provides similar numpy indexing behavior as if you were using multiple lists to index an array (e.g. arr[[0, 1], [0, 1]] ):

# index by integer array indices
In [12]: da = xray.DataArray(np.arange(56).reshape((7, 8)), dims=['x', 'y'])

In [13]: da
Out[13]: 
<xray.DataArray (x: 7, y: 8)>
array([[ 0,  1,  2, ...,  5,  6,  7],
       [ 8,  9, 10, ..., 13, 14, 15],
       [16, 17, 18, ..., 21, 22, 23],
       ..., 
       [32, 33, 34, ..., 37, 38, 39],
       [40, 41, 42, ..., 45, 46, 47],
       [48, 49, 50, ..., 53, 54, 55]])
Coordinates:
  * x        (x) int64 0 1 2 3 4 5 6
  * y        (y) int64 0 1 2 3 4 5 6 7

In [14]: da.isel_points(x=[0, 1, 6], y=[0, 1, 0])
Out[14]: 
<xray.DataArray (points: 3)>
array([ 0,  9, 48])
Coordinates:
    y        (points) int64 0 1 0
    x        (points) int64 0 1 6
  * points   (points) int64 0 1 2

There is also sel_points(), which analogously allows you to do point-wise indexing by label:

In [15]: times = pd.to_datetime(['2000-01-03', '2000-01-02', '2000-01-01'])

In [16]: arr.sel_points(space=['IA', 'IL', 'IN'], time=times)
Out[16]: 
<xray.DataArray (points: 3)>
array([  0.451,   0.377, -10.   ])
Coordinates:
    space    (points) |S2 'IA' 'IL' 'IN'
    time     (points) datetime64[ns] 2000-01-03 2000-01-02 2000-01-01
  * points   (points) int64 0 1 2

The equivalent pandas method to sel_points is lookup().

Dataset indexing

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

In [17]: ds = arr.to_dataset()

In [18]: ds.isel(space=[0], time=[0])
Out[18]: 
<xray.Dataset>
Dimensions:  (space: 1, time: 1)
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01
  * space    (space) |S2 'IA'
Data variables:
    None     (time, space) float64 0.127

In [19]: ds.sel(time='2000-01-01')
Out[19]: 
<xray.Dataset>
Dimensions:  (space: 3)
Coordinates:
    time     datetime64[ns] 2000-01-01
  * space    (space) |S2 'IA' 'IL' 'IN'
Data variables:
    None     (space) float64 0.127 -10.0 -10.0

In [20]: ds2 = da.to_dataset()

In [21]: ds2.isel_points(x=[0, 1, 6], y=[0, 1, 0], dim='points')
Out[21]: 
<xray.Dataset>
Dimensions:  (points: 3)
Coordinates:
    y        (points) int64 0 1 0
    x        (points) int64 0 1 6
  * points   (points) int64 0 1 2
Data variables:
    None     (points) int64 0 9 48

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 labeled dimensions:

In [22]: ds[dict(space=[0], time=[0])]
Out[22]: 
<xray.Dataset>
Dimensions:  (space: 1, time: 1)
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01
  * space    (space) |S2 'IA'
Data variables:
    None     (time, space) float64 0.127

In [23]: ds.loc[dict(time='2000-01-01')]
Out[23]: 
<xray.Dataset>
Dimensions:  (space: 3)
Coordinates:
    time     datetime64[ns] 2000-01-01
  * space    (space) |S2 'IA' 'IL' 'IN'
Data variables:
    None     (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 [24]: ds.drop(['IN', 'IL'], dim='space')
Out[24]: 
<xray.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) |S2 'IA'
Data variables:
    None     (time, space) float64 0.127 0.8972 0.4514 0.543

drop is both a Dataset and DataArray method.

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 [25]: data = xray.DataArray([1, 2, 3], dims='x')

In [26]: data.sel(x=[1.1, 1.9], method='nearest')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-26-a6b321b2eef8> in <module>()
----> 1 data.sel(x=[1.1, 1.9], method='nearest')

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/dataarray.pyc in sel(self, method, tolerance, **indexers)
    550         """
    551         return self.isel(**indexing.remap_label_indexers(
--> 552             self, indexers, method=method, tolerance=tolerance))
    553 
    554     def isel_points(self, dim='points', **indexers):

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/indexing.pyc in remap_label_indexers(data_obj, indexers, method, tolerance)
    171     return dict((dim, convert_label_indexer(data_obj[dim].to_index(), label,
    172                                             dim, method, tolerance))
--> 173                 for dim, label in iteritems(indexers))
    174 
    175 

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/indexing.pyc in <genexpr>((dim, label))
    171     return dict((dim, convert_label_indexer(data_obj[dim].to_index(), label,
    172                                             dim, method, tolerance))
--> 173                 for dim, label in iteritems(indexers))
    174 
    175 

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/indexing.pyc in convert_label_indexer(index, label, index_name, method, tolerance)
    156             indexer, = np.nonzero(label)
    157         else:
--> 158             indexer = index.get_indexer(label, **kwargs)
    159             if np.any(indexer < 0):
    160                 raise KeyError('not all values found in index %r'

/usr/lib/python2.7/dist-packages/pandas/core/index.pyc in get_indexer(self, target, method, limit)
   1115             this = self.astype(object)
   1116             target = target.astype(object)
-> 1117             return this.get_indexer(target, method=method, limit=limit)
   1118 
   1119         if not self.is_unique:

/usr/lib/python2.7/dist-packages/pandas/core/index.pyc in get_indexer(self, target, method, limit)
   1132             indexer = self._engine.get_indexer(target.values)
   1133         else:
-> 1134             raise ValueError('unrecognized method: %s' % method)
   1135 
   1136         return com._ensure_platform_int(indexer)

ValueError: unrecognized method: nearest

In [27]: data.sel(x=0.1, method='backfill')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-27-fea93a028543> in <module>()
----> 1 data.sel(x=0.1, method='backfill')

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/dataarray.pyc in sel(self, method, tolerance, **indexers)
    550         """
    551         return self.isel(**indexing.remap_label_indexers(
--> 552             self, indexers, method=method, tolerance=tolerance))
    553 
    554     def isel_points(self, dim='points', **indexers):

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/indexing.pyc in remap_label_indexers(data_obj, indexers, method, tolerance)
    171     return dict((dim, convert_label_indexer(data_obj[dim].to_index(), label,
    172                                             dim, method, tolerance))
--> 173                 for dim, label in iteritems(indexers))
    174 
    175 

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/indexing.pyc in <genexpr>((dim, label))
    171     return dict((dim, convert_label_indexer(data_obj[dim].to_index(), label,
    172                                             dim, method, tolerance))
--> 173                 for dim, label in iteritems(indexers))
    174 
    175 

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/indexing.pyc in convert_label_indexer(index, label, index_name, method, tolerance)
    152         label = np.asarray(label)
    153         if label.ndim == 0:
--> 154             indexer = index.get_loc(np.asscalar(label), **kwargs)
    155         elif label.dtype.kind == 'b':
    156             indexer, = np.nonzero(label)

TypeError: get_loc() got an unexpected keyword argument 'method'

In [28]: data.reindex(x=[0.5, 1, 1.5, 2, 2.5], method='pad')
Out[28]: 
<xray.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 [29]: data.reindex(x=[1.1, 1.5], method='nearest', tolerance=0.2)
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-29-c180e53b371f> in <module>()
----> 1 data.reindex(x=[1.1, 1.5], method='nearest', tolerance=0.2)

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/dataarray.pyc in reindex(self, method, tolerance, copy, **indexers)
    662         """
    663         ds = self._dataset.reindex(method=method, tolerance=tolerance,
--> 664                                    copy=copy, **indexers)
    665         return self._with_replaced_dataset(ds)
    666 

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/dataset.pyc in reindex(self, indexers, method, tolerance, copy, **kw_indexers)
   1302 
   1303         variables = alignment.reindex_variables(
-> 1304             self.variables, self.indexes, indexers, method, tolerance, copy=copy)
   1305         return self._replace_vars_and_dims(variables)
   1306 

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/alignment.pyc in reindex_variables(variables, indexes, indexers, method, tolerance, copy)
    150         if pd.__version__ < '0.17':
    151             raise NotImplementedError(
--> 152                 'the tolerance argument requires pandas v0.17 or newer')
    153         get_indexer_kwargs['tolerance'] = tolerance
    154 

NotImplementedError: the tolerance argument requires pandas v0.17 or newer

Using method='nearest' or a scalar argument with .sel() requires pandas version 0.16 or newer. Using tolerance requries pandas version 0.17 or newer.

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

In [30]: 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 [31]: data.sel(x=slice(0.9, 3.1))
Out[31]: 
<xray.DataArray (x: 3)>
array([1, 2, 3])
Coordinates:
  * x        (x) int64 0 1 2

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

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

In [33]: reversed_data.loc[3.1:0.9]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-33-5f52de481386> in <module>()
----> 1 reversed_data.loc[3.1:0.9]

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/dataarray.pyc in __getitem__(self, key)
     81 
     82     def __getitem__(self, key):
---> 83         return self.data_array[self._remap_key(key)]
     84 
     85     def __setitem__(self, key, value):

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/dataarray.pyc in _remap_key(self, key)
     78             key = indexing.expanded_indexer(key, self.data_array.ndim)
     79             return tuple(lookup_positions(dim, labels) for dim, labels
---> 80                          in zip(self.data_array.dims, key))
     81 
     82     def __getitem__(self, key):

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/dataarray.pyc in <genexpr>((dim, labels))
     77             # expand the indexer so we can handle Ellipsis
     78             key = indexing.expanded_indexer(key, self.data_array.ndim)
---> 79             return tuple(lookup_positions(dim, labels) for dim, labels
     80                          in zip(self.data_array.dims, key))
     81 

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/dataarray.pyc in lookup_positions(dim, labels)
     69         def lookup_positions(dim, labels):
     70             index = self.data_array.indexes[dim]
---> 71             return indexing.convert_label_indexer(index, labels)
     72 
     73         if utils.is_dict_like(key):

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/indexing.pyc in convert_label_indexer(index, label, index_name, method, tolerance)
    142         indexer = index.slice_indexer(_try_get_item(label.start),
    143                                       _try_get_item(label.stop),
--> 144                                       _try_get_item(label.step))
    145         if not isinstance(indexer, slice):
    146             # unlike pandas, in xray we never want to silently convert a slice

/usr/lib/python2.7/dist-packages/pandas/core/index.pyc in slice_indexer(self, start, end, step)
   1491         This function assumes that the data is sorted, so use at your own peril
   1492         """
-> 1493         start_slice, end_slice = self.slice_locs(start, end)
   1494 
   1495         # return a slice

/usr/lib/python2.7/dist-packages/pandas/core/index.pyc in slice_locs(self, start, end)
   1530         else:
   1531             try:
-> 1532                 start_slice = self.get_loc(start)
   1533 
   1534                 if not is_unique:

/usr/lib/python2.7/dist-packages/pandas/core/index.pyc in get_loc(self, key)
   1015         loc : int if unique index, possibly slice or mask if not
   1016         """
-> 1017         return self._engine.get_loc(_values_from_object(key))
   1018 
   1019     def get_value(self, series, key):

index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:3620)()

index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:3498)()

hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6930)()

hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6871)()

KeyError: 3

Masking with where

Indexing methods on xray 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 xray, use where():

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

In [35]: arr2.where(arr2.x + arr2.y < 4)
Out[35]: 
<xray.DataArray (x: 4, y: 4)>
array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,  nan],
       [  8.,   9.,  nan,  nan],
       [ 12.,  nan,  nan,  nan]])
Coordinates:
  * y        (y) int64 0 1 2 3
  * x        (x) int64 0 1 2 3

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 xray broadcasting and alignment rules for binary operations (e.g., +) between the object being indexed and the condition, as described in Computation:

In [36]: arr2.where(arr2.y < 2)
Out[36]: 
<xray.DataArray (x: 4, y: 4)>
array([[  0.,   1.,  nan,  nan],
       [  4.,   5.,  nan,  nan],
       [  8.,   9.,  nan,  nan],
       [ 12.,  13.,  nan,  nan]])
Coordinates:
  * y        (y) int64 0 1 2 3
  * x        (x) int64 0 1 2 3

Multi-dimensional indexing

Xray does not yet support efficient routines for generalized multi-dimensional indexing or regridding. However, we are definitely interested in adding support for this in the future (see GH475 for the ongoing discussion).

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, xray 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 xray than in pandas, so unlike pandas, xray does not produce SettingWithCopy warnings. However, you should still avoid assignment with chained indexing.

Orthogonal (outer) vs. vectorized indexing

Indexing with xray objects has one important difference from indexing numpy arrays: you can only use one-dimensional arrays to index xray objects, and each indexer is applied “orthogonally” along independent axes, instead of using numpy’s broadcasting rules to vectorize indexers. This means you can do indexing like this, which would require slightly more awkward syntax with numpy arrays:

In [37]: arr[arr['time.day'] > 1, arr['space'] != 'IL']
Out[37]: 
<xray.DataArray (time: 3, space: 2)>
array([[ 0.897,  0.336],
       [ 0.451,  0.123],
       [ 0.543,  0.448]])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-02 2000-01-03 2000-01-04
  * space    (space) |S2 'IA' 'IN'

This is a much simpler model than numpy’s advanced indexing. If you would like to do advanced-style array indexing in xray, you have several options:

In [38]: arr.values[arr.values > 0.5]
Out[38]: array([ 0.897,  0.84 ,  0.543])

Align and reindex

xray’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.

Xray 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 [39]: arr.reindex(space=['IA', 'CA'])
Out[39]: 
<xray.DataArray (time: 4, space: 2)>
array([[ 0.127,    nan],
       [ 0.897,    nan],
       [ 0.451,    nan],
       [ 0.543,    nan]])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  * space    (space) |S2 'IA' 'CA'

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

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

In [41]: baz = (10 * arr[:2, :2]).rename('baz')

In [42]: baz
Out[42]: 
<xray.DataArray 'baz' (time: 2, space: 2)>
array([[   1.27 , -100.   ],
       [   8.972,    3.767]])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02
  * space    (space) |S2 'IA' 'IL'

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

In [43]: foo.reindex_like(baz)
Out[43]: 
<xray.DataArray 'foo' (time: 2, space: 2)>
array([[  0.127, -10.   ],
       [  0.897,   0.377]])
Coordinates:
  * space    (space) object 'IA' 'IL'
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02

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

In [44]: baz.reindex_like(foo)
Out[44]: 
<xray.DataArray 'baz' (time: 4, space: 3)>
array([[   1.27 , -100.   ,      nan],
       [   8.972,    3.767,      nan],
       [     nan,      nan,      nan],
       [     nan,      nan,      nan]])
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
  * space    (space) object 'IA' 'IL' 'IN'

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

In [45]: xray.align(foo, baz, join='inner')
Out[45]: 
(<xray.DataArray 'foo' (time: 2, space: 2)>
 array([[  0.127, -10.   ],
        [  0.897,   0.377]])
 Coordinates:
   * space    (space) object 'IA' 'IL'
   * time     (time) datetime64[ns] 2000-01-01 2000-01-02,
 <xray.DataArray 'baz' (time: 2, space: 2)>
 array([[   1.27 , -100.   ],
        [   8.972,    3.767]])
 Coordinates:
   * time     (time) datetime64[ns] 2000-01-01 2000-01-02
   * space    (space) object 'IA' 'IL')

In [46]: xray.align(foo, baz, join='outer')
Out[46]: 
(<xray.DataArray 'foo' (time: 4, space: 3)>
 array([[  0.127, -10.   , -10.   ],
        [  0.897,   0.377,   0.336],
        [  0.451,   0.84 ,   0.123],
        [  0.543,   0.373,   0.448]])
 Coordinates:
   * space    (space) object 'IA' 'IL' 'IN'
   * time     (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04,
 <xray.DataArray 'baz' (time: 4, space: 3)>
 array([[   1.27 , -100.   ,      nan],
        [   8.972,    3.767,      nan],
        [     nan,      nan,      nan],
        [     nan,      nan,      nan]])
 Coordinates:
   * time     (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 2000-01-04
   * space    (space) object 'IA' 'IL' 'IN')

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

In [47]: ds
Out[47]: 
<xray.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) |S2 'IA' 'IL' 'IN'
Data variables:
    None     (time, space) float64 0.127 -10.0 -10.0 0.8972 0.3767 0.3362 ...

In [48]: ds.reindex_like(baz)
Out[48]: 
<xray.Dataset>
Dimensions:  (space: 2, time: 2)
Coordinates:
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02
  * space    (space) object 'IA' 'IL'
Data variables:
    None     (time, space) float64 0.127 -10.0 0.8972 0.3767

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

# this is a no-op, because there are no shared dimension names
In [50]: ds.reindex_like(other)
Out[50]: 
<xray.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) |S2 'IA' 'IL' 'IN'
Data variables:
    None     (time, space) float64 0.127 -10.0 -10.0 0.8972 0.3767 0.3362 ...