Computation

The labels associated with DataArray and Dataset objects enables some powerful shortcuts for computation, notably including aggregation and broadcasting by dimension names.

Basic array math

Arithmetic operations with a single DataArray automatically vectorize (like numpy) over all array values:

In [1]: arr = xr.DataArray(np.random.randn(2, 3),
   ...:                    [('x', ['a', 'b']), ('y', [10, 20, 30])])
   ...: 

In [2]: arr - 3
Out[2]: 
<xarray.DataArray (x: 2, y: 3)>
array([[-2.530888, -3.282863, -4.509059],
       [-4.135632, -1.787888, -3.173215]])
Coordinates:
  * x        (x) <U1 'a' 'b'
  * y        (y) int64 10 20 30

In [3]: abs(arr)
Out[3]: 
<xarray.DataArray (x: 2, y: 3)>
array([[ 0.469112,  0.282863,  1.509059],
       [ 1.135632,  1.212112,  0.173215]])
Coordinates:
  * x        (x) <U1 'a' 'b'
  * y        (y) int64 10 20 30

You can also use any of numpy’s or scipy’s many ufunc functions directly on a DataArray:

In [4]: np.sin(arr)
Out[4]: 
<xarray.DataArray (x: 2, y: 3)>
array([[ 0.452095, -0.279106, -0.998095],
       [-0.906801,  0.93636 , -0.17235 ]])
Coordinates:
  * x        (x) <U1 'a' 'b'
  * y        (y) int64 10 20 30

Data arrays also implement many numpy.ndarray methods:

In [5]: arr.round(2)
Out[5]: 
<xarray.DataArray (x: 2, y: 3)>
array([[ 0.47, -0.28, -1.51],
       [-1.14,  1.21, -0.17]])
Coordinates:
  * x        (x) <U1 'a' 'b'
  * y        (y) int64 10 20 30

In [6]: arr.T
Out[6]: 
<xarray.DataArray (y: 3, x: 2)>
array([[ 0.469112, -1.135632],
       [-0.282863,  1.212112],
       [-1.509059, -0.173215]])
Coordinates:
  * x        (x) <U1 'a' 'b'
  * y        (y) int64 10 20 30

Missing values

xarray objects borrow the isnull(), notnull(), count(), dropna() and fillna() methods for working with missing data from pandas:

In [7]: x = xr.DataArray([0, 1, np.nan, np.nan, 2], dims=['x'])

In [8]: x.isnull()
Out[8]: 
<xarray.DataArray (x: 5)>
array([False, False,  True,  True, False], dtype=bool)
Dimensions without coordinates: x

In [9]: x.notnull()
Out[9]: 
<xarray.DataArray (x: 5)>
array([ True,  True, False, False,  True], dtype=bool)
Dimensions without coordinates: x

In [10]: x.count()
Out[10]: 
<xarray.DataArray ()>
array(3)

In [11]: x.dropna(dim='x')
Out[11]: 
<xarray.DataArray (x: 3)>
array([ 0.,  1.,  2.])
Dimensions without coordinates: x

In [12]: x.fillna(-1)
Out[12]: 
<xarray.DataArray (x: 5)>
array([ 0.,  1., -1., -1.,  2.])
Dimensions without coordinates: x

Like pandas, xarray uses the float value np.nan (not-a-number) to represent missing values.

Aggregation

Aggregation methods have been updated to take a dim argument instead of axis. This allows for very intuitive syntax for aggregation methods that are applied along particular dimension(s):

In [13]: arr.sum(dim='x')
Out[13]: 
<xarray.DataArray (y: 3)>
array([-0.66652 ,  0.929249, -1.682273])
Coordinates:
  * y        (y) int64 10 20 30

In [14]: arr.std(['x', 'y'])
Out[14]: 
<xarray.DataArray ()>
array(0.9156385956757354)

In [15]: arr.min()
Out[15]: 
<xarray.DataArray ()>
array(-1.5090585031735124)

If you need to figure out the axis number for a dimension yourself (say, for wrapping code designed to work with numpy arrays), you can use the get_axis_num() method:

In [16]: arr.get_axis_num('y')
Out[16]: 1

These operations automatically skip missing values, like in pandas:

In [17]: xr.DataArray([1, 2, np.nan, 3]).mean()
Out[17]: 
<xarray.DataArray ()>
array(2.0)

If desired, you can disable this behavior by invoking the aggregation method with skipna=False.

Rolling window operations

DataArray objects include a rolling() method. This method supports rolling window aggregation:

In [18]: arr = xr.DataArray(np.arange(0, 7.5, 0.5).reshape(3, 5),
   ....:                    dims=('x', 'y'))
   ....: 

In [19]: arr
Out[19]: 
<xarray.DataArray (x: 3, y: 5)>
array([[ 0. ,  0.5,  1. ,  1.5,  2. ],
       [ 2.5,  3. ,  3.5,  4. ,  4.5],
       [ 5. ,  5.5,  6. ,  6.5,  7. ]])
Dimensions without coordinates: x, y

rolling() is applied along one dimension using the name of the dimension as a key (e.g. y) and the window size as the value (e.g. 3). We get back a Rolling object:

In [20]: arr.rolling(y=3)
Out[20]: DataArrayRolling [window->3,center->False,dim->y]

The label position and minimum number of periods in the rolling window are controlled by the center and min_periods arguments:

In [21]: arr.rolling(y=3, min_periods=2, center=True)
Out[21]: DataArrayRolling [window->3,min_periods->2,center->True,dim->y]

Aggregation and summary methods can be applied directly to the Rolling object:

In [22]: r = arr.rolling(y=3)

In [23]: r.mean()
Out[23]: 
<xarray.DataArray (x: 3, y: 5)>
array([[ nan,  nan,  0.5,  1. ,  1.5],
       [ nan,  nan,  3. ,  3.5,  4. ],
       [ nan,  nan,  5.5,  6. ,  6.5]])
Dimensions without coordinates: x, y

In [24]: r.reduce(np.std)
Out[24]: 
<xarray.DataArray (x: 3, y: 5)>
array([[      nan,       nan,  0.408248,  0.408248,  0.408248],
       [      nan,       nan,  0.408248,  0.408248,  0.408248],
       [      nan,       nan,  0.408248,  0.408248,  0.408248]])
Dimensions without coordinates: x, y

Note that rolling window aggregations are much faster (both asymptotically and because they avoid a loop in Python) when bottleneck is installed. Otherwise, we fall back to a slower, pure Python implementation.

Finally, we can manually iterate through Rolling objects:

In [25]: for label, arr_window in r:
   # arr_window is a view of x

Broadcasting by dimension name

DataArray objects are automatically align themselves (“broadcasting” in the numpy parlance) by dimension name instead of axis order. With xarray, you do not need to transpose arrays or insert dimensions of length 1 to get array operations to work, as commonly done in numpy with np.reshape() or np.newaxis.

This is best illustrated by a few examples. Consider two one-dimensional arrays with different sizes aligned along different dimensions:

In [26]: a = xr.DataArray([1, 2], [('x', ['a', 'b'])])

In [27]: a
Out[27]: 
<xarray.DataArray (x: 2)>
array([1, 2])
Coordinates:
  * x        (x) <U1 'a' 'b'

In [28]: b = xr.DataArray([-1, -2, -3], [('y', [10, 20, 30])])

In [29]: b
Out[29]: 
<xarray.DataArray (y: 3)>
array([-1, -2, -3])
Coordinates:
  * y        (y) int64 10 20 30

With xarray, we can apply binary mathematical operations to these arrays, and their dimensions are expanded automatically:

In [30]: a * b
Out[30]: 
<xarray.DataArray (x: 2, y: 3)>
array([[-1, -2, -3],
       [-2, -4, -6]])
Coordinates:
  * x        (x) <U1 'a' 'b'
  * y        (y) int64 10 20 30

Moreover, dimensions are always reordered to the order in which they first appeared:

In [31]: c = xr.DataArray(np.arange(6).reshape(3, 2), [b['y'], a['x']])

In [32]: c
Out[32]: 
<xarray.DataArray (y: 3, x: 2)>
array([[0, 1],
       [2, 3],
       [4, 5]])
Coordinates:
  * y        (y) int64 10 20 30
  * x        (x) <U1 'a' 'b'

In [33]: a + c
Out[33]: 
<xarray.DataArray (x: 2, y: 3)>
array([[1, 3, 5],
       [3, 5, 7]])
Coordinates:
  * x        (x) <U1 'a' 'b'
  * y        (y) int64 10 20 30

This means, for example, that you always subtract an array from its transpose:

In [34]: c - c.T
Out[34]: 
<xarray.DataArray (y: 3, x: 2)>
array([[0, 0],
       [0, 0],
       [0, 0]])
Coordinates:
  * y        (y) int64 10 20 30
  * x        (x) <U1 'a' 'b'

You can explicitly broadcast xaray data structures by using the broadcast() function:

In [35]: a2, b2 = xr.broadcast(a, b)

In [36]: a2
Out[36]: 
<xarray.DataArray (x: 2, y: 3)>
array([[1, 1, 1],
       [2, 2, 2]])
Coordinates:
  * x        (x) <U1 'a' 'b'
  * y        (y) int64 10 20 30

In [37]: b2
Out[37]: 
<xarray.DataArray (x: 2, y: 3)>
array([[-1, -2, -3],
       [-1, -2, -3]])
Coordinates:
  * y        (y) int64 10 20 30
  * x        (x) <U1 'a' 'b'

Automatic alignment

xarray enforces alignment between index Coordinates (that is, coordinates with the same name as a dimension, marked by *) on objects used in binary operations.

Similarly to pandas, this alignment is automatic for arithmetic on binary operations. The default result of a binary operation is by the intersection (not the union) of coordinate labels:

In [38]: arr = xr.DataArray(np.arange(3), [('x', range(3))])

In [39]: arr + arr[:-1]
Out[39]: 
<xarray.DataArray (x: 2)>
array([0, 2])
Coordinates:
  * x        (x) int64 0 1

If coordinate values for a dimension are missing on either argument, all matching dimensions must have the same size:

In [40]: In [1]: arr + xr.DataArray([1, 2], dims='x')
   ....: ValueError: arguments without labels along dimension 'x' cannot be aligned because they have different dimension size(s) {2} than the size of the aligned dimension labels: 3
   ....: 

However, one can explicitly change this default automatic alignment type (“inner”) via set_options() in context manager:

In [41]: with xr.set_options(arithmetic_join="outer"):
   ....:     arr + arr[:1]
   ....: 

In [42]: arr + arr[:1]
Out[42]: 
<xarray.DataArray (x: 1)>
array([0])
Coordinates:
  * x        (x) int64 0

Before loops or performance critical code, it’s a good idea to align arrays explicitly (e.g., by putting them in the same Dataset or using align()) to avoid the overhead of repeated alignment with each operation. See Align and reindex for more details.

Note

There is no automatic alignment between arguments when performing in-place arithmetic operations such as +=. You will need to use manual alignment. This ensures in-place arithmetic never needs to modify data types.

Coordinates

Although index coordinates are aligned, other coordinates are not, and if their values conflict, they will be dropped. This is necessary, for example, because indexing turns 1D coordinates into scalar coordinates:

In [43]: arr[0]
Out[43]: 
<xarray.DataArray ()>
array(0)
Coordinates:
    x        int64 0

In [44]: arr[1]
Out[44]: 
<xarray.DataArray ()>
array(1)
Coordinates:
    x        int64 1

# notice that the scalar coordinate 'x' is silently dropped
In [45]: arr[1] - arr[0]
Out[45]: 
<xarray.DataArray ()>
array(1)

Still, xarray will persist other coordinates in arithmetic, as long as there are no conflicting values:

# only one argument has the 'x' coordinate
In [46]: arr[0] + 1
Out[46]: 
<xarray.DataArray ()>
array(1)
Coordinates:
    x        int64 0

# both arguments have the same 'x' coordinate
In [47]: arr[0] - arr[0]
Out[47]: 
<xarray.DataArray ()>
array(0)
Coordinates:
    x        int64 0

Math with datasets

Datasets support arithmetic operations by automatically looping over all data variables:

In [48]: ds = xr.Dataset({'x_and_y': (('x', 'y'), np.random.randn(3, 5)),
   ....:                  'x_only': ('x', np.random.randn(3))},
   ....:                  coords=arr.coords)
   ....: 

In [49]: ds > 0
Out[49]: 
<xarray.Dataset>
Dimensions:  (x: 3, y: 5)
Coordinates:
  * x        (x) int64 0 1 2
Dimensions without coordinates: y
Data variables:
    x_and_y  (x, y) bool True False False False False True True False False ...
    x_only   (x) bool True False True

Datasets support most of the same methods found on data arrays:

In [50]: ds.mean(dim='x')
Out[50]: 
<xarray.Dataset>
Dimensions:  (y: 5)
Dimensions without coordinates: y
Data variables:
    x_and_y  (y) float64 0.2553 0.08145 -0.4308 -1.411 -0.2989
    x_only   float64 -0.2799

In [51]: abs(ds)
Out[51]: 
<xarray.Dataset>
Dimensions:  (x: 3)
Coordinates:
  * x        (x) int64 0 1 2
Data variables:
    x_and_y  (x, y) float64 0.1192 1.044 0.8618 2.105 0.4949 1.072 0.7216 ...
    x_only   (x) float64 0.1136 1.478 0.525

Unfortunately, a limitation of the current version of numpy means that we cannot override ufuncs for datasets, because datasets cannot be written as a single array [1]. apply() works around this limitation, by applying the given function to each variable in the dataset:

In [52]: ds.apply(np.sin)
Out[52]: 
<xarray.Dataset>
Dimensions:  (x: 3, y: 5)
Coordinates:
  * x        (x) int64 0 1 2
Dimensions without coordinates: y
Data variables:
    x_and_y  (x, y) float64 0.1189 -0.8645 -0.759 -0.8609 -0.475 0.8781 ...
    x_only   (x) float64 0.1134 -0.9957 0.5012

Datasets also use looping over variables for broadcasting in binary arithmetic. You can do arithmetic between any DataArray and a dataset:

In [53]: ds + arr
Out[53]: 
<xarray.Dataset>
Dimensions:  (x: 3, y: 5)
Coordinates:
  * x        (x) int64 0 1 2
Dimensions without coordinates: y
Data variables:
    x_and_y  (x, y) float64 0.1192 -1.044 -0.8618 -2.105 -0.4949 2.072 1.722 ...
    x_only   (x) float64 0.1136 -0.4784 2.525

Arithmetic between two datasets matches data variables of the same name:

In [54]: ds2 = xr.Dataset({'x_and_y': 0, 'x_only': 100})

In [55]: ds - ds2
Out[55]: 
<xarray.Dataset>
Dimensions:  (x: 3, y: 5)
Coordinates:
  * x        (x) int64 0 1 2
Dimensions without coordinates: y
Data variables:
    x_and_y  (x, y) float64 0.1192 -1.044 -0.8618 -2.105 -0.4949 1.072 ...
    x_only   (x) float64 -99.89 -101.5 -99.48

Similarly to index based alignment, the result has the intersection of all matching data variables.

[1]In some future version of NumPy, we should be able to override ufuncs for datasets by making use of __numpy_ufunc__.