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:

arr = xr.DataArray(
 np.random.default_rng(0).random((2, 3)),
 [("x", ["a", "b"]), ("y", [10, 20, 30])],
)
arr - 3
<xarray.DataArray (x: 2, y: 3)> Size: 48B
array([[-2.36303831, -2.73021329, -2.95902648],
 [-2.98347236, -2.18672976, -2.08724442]])
Coordinates:
 * x (x) <U1 8B 'a' 'b'
 * y (y) int64 24B 10 20 30
xarray.DataArray
  • x: 2
  • y: 3
  • -2.363 -2.73 -2.959 -2.983 -2.187 -2.087
    array([[-2.36303831, -2.73021329, -2.95902648],
     [-2.98347236, -2.18672976, -2.08724442]])
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])
abs(arr)
<xarray.DataArray (x: 2, y: 3)> Size: 48B
array([[0.63696169, 0.26978671, 0.04097352],
 [0.01652764, 0.81327024, 0.91275558]])
Coordinates:
 * x (x) <U1 8B 'a' 'b'
 * y (y) int64 24B 10 20 30
xarray.DataArray
  • x: 2
  • y: 3
  • 0.637 0.2698 0.04097 0.01653 0.8133 0.9128
    array([[0.63696169, 0.26978671, 0.04097352],
     [0.01652764, 0.81327024, 0.91275558]])
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])

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

np.sin(arr)
<xarray.DataArray (x: 2, y: 3)> Size: 48B
array([[0.59475567, 0.26652587, 0.04096206],
 [0.01652688, 0.72653812, 0.79119196]])
Coordinates:
 * x (x) <U1 8B 'a' 'b'
 * y (y) int64 24B 10 20 30
xarray.DataArray
  • x: 2
  • y: 3
  • 0.5948 0.2665 0.04096 0.01653 0.7265 0.7912
    array([[0.59475567, 0.26652587, 0.04096206],
     [0.01652688, 0.72653812, 0.79119196]])
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])

Use where() to conditionally switch between values:

xr.where(arr > 0, "positive", "negative")
<xarray.DataArray (x: 2, y: 3)> Size: 192B
array([['positive', 'positive', 'positive'],
 ['positive', 'positive', 'positive']], dtype='<U8')
Coordinates:
 * x (x) <U1 8B 'a' 'b'
 * y (y) int64 24B 10 20 30
xarray.DataArray
  • x: 2
  • y: 3
  • 'positive' 'positive' 'positive' 'positive' 'positive' 'positive'
    array([['positive', 'positive', 'positive'],
     ['positive', 'positive', 'positive']], dtype='<U8')
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])

Use @ to compute the dot() product:

arr @ arr
<xarray.DataArray ()> Size: 8B
array(1.97498828)
xarray.DataArray
  • 1.975
    array(1.97498828)

Data arrays also implement many numpy.ndarray methods:

arr.round(2)
<xarray.DataArray (x: 2, y: 3)> Size: 48B
array([[0.64, 0.27, 0.04],
 [0.02, 0.81, 0.91]])
Coordinates:
 * x (x) <U1 8B 'a' 'b'
 * y (y) int64 24B 10 20 30
xarray.DataArray
  • x: 2
  • y: 3
  • 0.64 0.27 0.04 0.02 0.81 0.91
    array([[0.64, 0.27, 0.04],
     [0.02, 0.81, 0.91]])
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])
arr.T
<xarray.DataArray (y: 3, x: 2)> Size: 48B
array([[0.63696169, 0.01652764],
 [0.26978671, 0.81327024],
 [0.04097352, 0.91275558]])
Coordinates:
 * y (y) int64 24B 10 20 30
 * x (x) <U1 8B 'a' 'b'
xarray.DataArray
  • y: 3
  • x: 2
  • 0.637 0.01653 0.2698 0.8133 0.04097 0.9128
    array([[0.63696169, 0.01652764],
     [0.26978671, 0.81327024],
     [0.04097352, 0.91275558]])
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')
intarr = xr.DataArray([0, 1, 2, 3, 4, 5])
intarr << 2 # only supported for int types
<xarray.DataArray (dim_0: 6)> Size: 48B
array([ 0, 4, 8, 12, 16, 20])
Dimensions without coordinates: dim_0
xarray.DataArray
  • dim_0: 6
  • 0 4 8 12 16 20
    array([ 0, 4, 8, 12, 16, 20])
intarr >> 1
<xarray.DataArray (dim_0: 6)> Size: 48B
array([0, 0, 1, 1, 2, 2])
Dimensions without coordinates: dim_0
xarray.DataArray
  • dim_0: 6
  • 0 0 1 1 2 2
    array([0, 0, 1, 1, 2, 2])

Missing values#

Xarray represents missing values using the "NaN" (Not a Number) value from NumPy, which is a special floating-point value that indicates a value that is undefined or unrepresentable. There are several methods for handling missing values in xarray:

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

isnull() is a method in xarray that can be used to check for missing or null values in an xarray object. It returns a new xarray object with the same dimensions as the original object, but with boolean values indicating where missing values are present.

x = xr.DataArray([0, 1, np.nan, np.nan, 2], dims=["x"])
x.isnull()
<xarray.DataArray (x: 5)> Size: 5B
array([False, False, True, True, False])
Dimensions without coordinates: x
xarray.DataArray
  • x: 5
  • False False True True False
    array([False, False, True, True, False])

In this example, the third and fourth elements of ‘x’ are NaN, so the resulting DataArray object has ‘True’ values in the third and fourth positions and ‘False’ values in the other positions.

notnull() is a method in xarray that can be used to check for non-missing or non-null values in an xarray object. It returns a new xarray object with the same dimensions as the original object, but with boolean values indicating where non-missing values are present.

x = xr.DataArray([0, 1, np.nan, np.nan, 2], dims=["x"])
x.notnull()
<xarray.DataArray (x: 5)> Size: 5B
array([ True, True, False, False, True])
Dimensions without coordinates: x
xarray.DataArray
  • x: 5
  • True True False False True
    array([ True, True, False, False, True])

In this example, the first two and the last elements of x are not NaN, so the resulting DataArray object has ‘True’ values in these positions, and ‘False’ values in the third and fourth positions where NaN is located.

count() is a method in xarray that can be used to count the number of non-missing values along one or more dimensions of an xarray object. It returns a new xarray object with the same dimensions as the original object, but with each element replaced by the count of non-missing values along the specified dimensions.

x = xr.DataArray([0, 1, np.nan, np.nan, 2], dims=["x"])
x.count()
<xarray.DataArray ()> Size: 8B
array(3)
xarray.DataArray
  • 3
    array(3)

In this example, ‘x’ has five elements, but two of them are NaN, so the resulting DataArray object having a single element containing the value ‘3’, which represents the number of non-null elements in x.

dropna() is a method in xarray that can be used to remove missing or null values from an xarray object. It returns a new xarray object with the same dimensions as the original object, but with missing values removed.

x = xr.DataArray([0, 1, np.nan, np.nan, 2], dims=["x"])
x.dropna(dim="x")
<xarray.DataArray (x: 3)> Size: 24B
array([0., 1., 2.])
Dimensions without coordinates: x
xarray.DataArray
  • x: 3
  • 0.0 1.0 2.0
    array([0., 1., 2.])

In this example, on calling x.dropna(dim="x") removes any missing values and returns a new DataArray object with only the non-null elements [0, 1, 2] of ‘x’, in the original order.

fillna() is a method in xarray that can be used to fill missing or null values in an xarray object with a specified value or method. It returns a new xarray object with the same dimensions as the original object, but with missing values filled.

x = xr.DataArray([0, 1, np.nan, np.nan, 2], dims=["x"])
x.fillna(-1)
<xarray.DataArray (x: 5)> Size: 40B
array([ 0., 1., -1., -1., 2.])
Dimensions without coordinates: x
xarray.DataArray
  • x: 5
  • 0.0 1.0 -1.0 -1.0 2.0
    array([ 0., 1., -1., -1., 2.])

In this example, there are two NaN values in ‘x’, so calling x.fillna(-1) replaces these values with -1 and returns a new DataArray object with five elements, containing the values [0, 1, -1, -1, 2] in the original order.

ffill() is a method in xarray that can be used to forward fill (or fill forward) missing values in an xarray object along one or more dimensions. It returns a new xarray object with the same dimensions as the original object, but with missing values replaced by the last non-missing value along the specified dimensions.

x = xr.DataArray([0, 1, np.nan, np.nan, 2], dims=["x"])
x.ffill("x")
<xarray.DataArray (x: 5)> Size: 40B
array([0., 1., 1., 1., 2.])
Dimensions without coordinates: x
xarray.DataArray
  • x: 5
  • 0.0 1.0 1.0 1.0 2.0
    array([0., 1., 1., 1., 2.])

In this example, there are two NaN values in ‘x’, so calling x.ffill("x") fills these values with the last non-null value in the same dimension, which are 0 and 1, respectively. The resulting DataArray object has five elements, containing the values [0, 1, 1, 1, 2] in the original order.

bfill() is a method in xarray that can be used to backward fill (or fill backward) missing values in an xarray object along one or more dimensions. It returns a new xarray object with the same dimensions as the original object, but with missing values replaced by the next non-missing value along the specified dimensions.

x = xr.DataArray([0, 1, np.nan, np.nan, 2], dims=["x"])
x.bfill("x")
<xarray.DataArray (x: 5)> Size: 40B
array([0., 1., 2., 2., 2.])
Dimensions without coordinates: x
xarray.DataArray
  • x: 5
  • 0.0 1.0 2.0 2.0 2.0
    array([0., 1., 2., 2., 2.])

In this example, there are two NaN values in ‘x’, so calling x.bfill("x") fills these values with the next non-null value in the same dimension, which are 2 and 2, respectively. The resulting DataArray object has five elements, containing the values [0, 1, 2, 2, 2] in the original order.

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

Xarray objects also have an interpolate_na() method for filling missing values via 1D interpolation. It returns a new xarray object with the same dimensions as the original object, but with missing values interpolated.

x = xr.DataArray(
 [0, 1, np.nan, np.nan, 2],
 dims=["x"],
 coords={"xx": xr.Variable("x", [0, 1, 1.1, 1.9, 3])},
)
x.interpolate_na(dim="x", method="linear", use_coordinate="xx")
<xarray.DataArray (x: 5)> Size: 40B
array([0. , 1. , 1.05, 1.45, 2. ])
Coordinates:
 xx (x) float64 40B 0.0 1.0 1.1 1.9 3.0
Dimensions without coordinates: x
xarray.DataArray
  • x: 5
  • 0.0 1.0 1.05 1.45 2.0
    array([0. , 1. , 1.05, 1.45, 2. ])
    • xx
      (x)
      float64
      0.0 1.0 1.1 1.9 3.0
      array([0. , 1. , 1.1, 1.9, 3. ])

In this example, there are two NaN values in ‘x’, so calling x.interpolate_na(dim="x", method="linear", use_coordinate="xx") fills these values with interpolated values along the "x" dimension using linear interpolation based on the values of the xx coordinate. The resulting DataArray object has five elements, containing the values [0., 1., 1.05, 1.45, 2.] in the original order. Note that the interpolated values are calculated based on the values of the ‘xx’ coordinate, which has non-integer values, resulting in non-integer interpolated values.

Note that xarray slightly diverges from the pandas interpolate syntax by providing the use_coordinate keyword which facilitates a clear specification of which values to use as the index in the interpolation. Xarray also provides the max_gap keyword argument to limit the interpolation to data gaps of length max_gap or smaller. See interpolate_na() for more.

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):

arr.sum(dim="x")
<xarray.DataArray (y: 3)> Size: 24B
array([0.65348932, 1.08305695, 0.9537291 ])
Coordinates:
 * y (y) int64 24B 10 20 30
xarray.DataArray
  • y: 3
  • 0.6535 1.083 0.9537
    array([0.65348932, 1.08305695, 0.9537291 ])
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])
arr.std(["x", "y"])
<xarray.DataArray ()> Size: 8B
array(0.35793963)
xarray.DataArray
  • 0.3579
    array(0.35793963)
arr.min()
<xarray.DataArray ()> Size: 8B
array(0.01652764)
xarray.DataArray
  • 0.01653
    array(0.01652764)

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:

arr.get_axis_num("y")
1

These operations automatically skip missing values, like in pandas:

xr.DataArray([1, 2, np.nan, 3]).mean()
<xarray.DataArray ()> Size: 8B
array(2.)
xarray.DataArray
  • 2.0
    array(2.)

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:

arr = xr.DataArray(np.arange(0, 7.5, 0.5).reshape(3, 5), dims=("x", "y"))
arr
<xarray.DataArray (x: 3, y: 5)> Size: 120B
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
xarray.DataArray
  • x: 3
  • y: 5
  • 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0
    array([[0. , 0.5, 1. , 1.5, 2. ],
     [2.5, 3. , 3.5, 4. , 4.5],
     [5. , 5.5, 6. , 6.5, 7. ]])

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:

arr.rolling(y=3)
DataArrayRolling [y->3]

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

r = arr.rolling(y=3)
r.reduce(np.std)
<xarray.DataArray (x: 3, y: 5)> Size: 120B
array([[ nan, nan, 0.40824829, 0.40824829, 0.40824829],
 [ nan, nan, 0.40824829, 0.40824829, 0.40824829],
 [ nan, nan, 0.40824829, 0.40824829, 0.40824829]])
Dimensions without coordinates: x, y
xarray.DataArray
  • x: 3
  • y: 5
  • nan nan 0.4082 0.4082 0.4082 nan ... nan nan 0.4082 0.4082 0.4082
    array([[ nan, nan, 0.40824829, 0.40824829, 0.40824829],
     [ nan, nan, 0.40824829, 0.40824829, 0.40824829],
     [ nan, nan, 0.40824829, 0.40824829, 0.40824829]])
r.mean()
<xarray.DataArray (x: 3, y: 5)> Size: 120B
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
xarray.DataArray
  • x: 3
  • y: 5
  • nan nan 0.5 1.0 1.5 nan nan 3.0 3.5 4.0 nan nan 5.5 6.0 6.5
    array([[nan, nan, 0.5, 1. , 1.5],
     [nan, nan, 3. , 3.5, 4. ],
     [nan, nan, 5.5, 6. , 6.5]])

Aggregation results are assigned the coordinate at the end of each window by default, but can be centered by passing center=True when constructing the Rolling object:

r = arr.rolling(y=3, center=True)
r.mean()
<xarray.DataArray (x: 3, y: 5)> Size: 120B
array([[nan, 0.5, 1. , 1.5, nan],
 [nan, 3. , 3.5, 4. , nan],
 [nan, 5.5, 6. , 6.5, nan]])
Dimensions without coordinates: x, y
xarray.DataArray
  • x: 3
  • y: 5
  • nan 0.5 1.0 1.5 nan nan 3.0 3.5 4.0 nan nan 5.5 6.0 6.5 nan
    array([[nan, 0.5, 1. , 1.5, nan],
     [nan, 3. , 3.5, 4. , nan],
     [nan, 5.5, 6. , 6.5, nan]])

As can be seen above, aggregations of windows which overlap the border of the array produce nans. Setting min_periods in the call to rolling changes the minimum number of observations within the window required to have a value when aggregating:

r = arr.rolling(y=3, min_periods=2)
r.mean()
<xarray.DataArray (x: 3, y: 5)> Size: 120B
array([[ nan, 0.25, 0.5 , 1. , 1.5 ],
 [ nan, 2.75, 3. , 3.5 , 4. ],
 [ nan, 5.25, 5.5 , 6. , 6.5 ]])
Dimensions without coordinates: x, y
xarray.DataArray
  • x: 3
  • y: 5
  • nan 0.25 0.5 1.0 1.5 nan 2.75 3.0 3.5 4.0 nan 5.25 5.5 6.0 6.5
    array([[ nan, 0.25, 0.5 , 1. , 1.5 ],
     [ nan, 2.75, 3. , 3.5 , 4. ],
     [ nan, 5.25, 5.5 , 6. , 6.5 ]])
r = arr.rolling(y=3, center=True, min_periods=2)
r.mean()
<xarray.DataArray (x: 3, y: 5)> Size: 120B
array([[0.25, 0.5 , 1. , 1.5 , 1.75],
 [2.75, 3. , 3.5 , 4. , 4.25],
 [5.25, 5.5 , 6. , 6.5 , 6.75]])
Dimensions without coordinates: x, y
xarray.DataArray
  • x: 3
  • y: 5
  • 0.25 0.5 1.0 1.5 1.75 2.75 3.0 3.5 4.0 4.25 5.25 5.5 6.0 6.5 6.75
    array([[0.25, 0.5 , 1. , 1.5 , 1.75],
     [2.75, 3. , 3.5 , 4. , 4.25],
     [5.25, 5.5 , 6. , 6.5 , 6.75]])

From version 0.17, xarray supports multidimensional rolling,

r = arr.rolling(x=2, y=3, min_periods=2)
r.mean()
<xarray.DataArray (x: 3, y: 5)> Size: 120B
array([[ nan, 0.25, 0.5 , 1. , 1.5 ],
 [1.25, 1.5 , 1.75, 2.25, 2.75],
 [3.75, 4. , 4.25, 4.75, 5.25]])
Dimensions without coordinates: x, y
xarray.DataArray
  • x: 3
  • y: 5
  • nan 0.25 0.5 1.0 1.5 1.25 1.5 1.75 2.25 2.75 3.75 4.0 4.25 4.75 5.25
    array([[ nan, 0.25, 0.5 , 1. , 1.5 ],
     [1.25, 1.5 , 1.75, 2.25, 2.75],
     [3.75, 4. , 4.25, 4.75, 5.25]])

Tip

Note that rolling window aggregations are faster and use less memory when bottleneck is installed. This only applies to numpy-backed xarray objects with 1d-rolling.

We can also manually iterate through Rolling objects:

for label, arr_window in r:
 # arr_window is a view of x
 ...

While rolling provides a simple moving average, DataArray also supports an exponential moving average with rolling_exp(). This is similar to pandas’ ewm method. numbagg is required.

arr.rolling_exp(y=3).mean()

The rolling_exp method takes a window_type kwarg, which can be 'alpha', 'com' (for center-of-mass), 'span', and 'halflife'. The default is span.

Finally, the rolling object has a construct method which returns a view of the original DataArray with the windowed dimension in the last position. You can use this for more advanced rolling operations such as strided rolling, windowed rolling, convolution, short-time FFT etc.

# rolling with 2-point stride
rolling_da = r.construct(x="x_win", y="y_win", stride=2)
rolling_da
<xarray.DataArray (x: 2, y: 3, x_win: 2, y_win: 3)> Size: 288B
array([[[[nan, nan, nan],
 [nan, nan, 0. ]],
 [[nan, nan, nan],
 [0. , 0.5, 1. ]],
 [[nan, nan, nan],
 [1. , 1.5, 2. ]]],
 [[[nan, nan, 2.5],
 [nan, nan, 5. ]],
 [[2.5, 3. , 3.5],
 [5. , 5.5, 6. ]],
 [[3.5, 4. , 4.5],
 [6. , 6.5, 7. ]]]])
Dimensions without coordinates: x, y, x_win, y_win
xarray.DataArray
  • x: 2
  • y: 3
  • x_win: 2
  • y_win: 3
  • nan nan nan nan nan 0.0 nan nan ... 5.5 6.0 3.5 4.0 4.5 6.0 6.5 7.0
    array([[[[nan, nan, nan],
     [nan, nan, 0. ]],
     [[nan, nan, nan],
     [0. , 0.5, 1. ]],
     [[nan, nan, nan],
     [1. , 1.5, 2. ]]],
     [[[nan, nan, 2.5],
     [nan, nan, 5. ]],
     [[2.5, 3. , 3.5],
     [5. , 5.5, 6. ]],
     [[3.5, 4. , 4.5],
     [6. , 6.5, 7. ]]]])
rolling_da.mean(["x_win", "y_win"], skipna=False)
<xarray.DataArray (x: 2, y: 3)> Size: 48B
array([[ nan, nan, nan],
 [ nan, 4.25, 5.25]])
Dimensions without coordinates: x, y
xarray.DataArray
  • x: 2
  • y: 3
  • nan nan nan nan 4.25 5.25
    array([[ nan, nan, nan],
     [ nan, 4.25, 5.25]])

Because the DataArray given by r.construct('window_dim') is a view of the original array, it is memory efficient. You can also use construct to compute a weighted rolling sum:

weight = xr.DataArray([0.25, 0.5, 0.25], dims=["window"])
arr.rolling(y=3).construct(y="window").dot(weight)
<xarray.DataArray (x: 3, y: 5)> Size: 120B
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
xarray.DataArray
  • x: 3
  • y: 5
  • nan nan 0.5 1.0 1.5 nan nan 3.0 3.5 4.0 nan nan 5.5 6.0 6.5
    array([[nan, nan, 0.5, 1. , 1.5],
     [nan, nan, 3. , 3.5, 4. ],
     [nan, nan, 5.5, 6. , 6.5]])

Note

numpy’s Nan-aggregation functions such as nansum copy the original array. In xarray, we internally use these functions in our aggregation methods (such as .sum()) if skipna argument is not specified or set to True. This means rolling_da.mean('window_dim') is memory inefficient. To avoid this, use skipna=False as the above example.

Weighted array reductions#

DataArray and Dataset objects include DataArray.weighted() and Dataset.weighted() array reduction methods. They currently support weighted sum, mean, std, var and quantile.

coords = dict(month=("month", [1, 2, 3]))
prec = xr.DataArray([1.1, 1.0, 0.9], dims=("month",), coords=coords)
weights = xr.DataArray([31, 28, 31], dims=("month",), coords=coords)

Create a weighted object:

weighted_prec = prec.weighted(weights)
weighted_prec
DataArrayWeighted with weights along dimensions: month

Calculate the weighted sum:

weighted_prec.sum()
<xarray.DataArray ()> Size: 8B
array(90.)
xarray.DataArray
  • 90.0
    array(90.)

Calculate the weighted mean:

weighted_prec.mean(dim="month")
<xarray.DataArray ()> Size: 8B
array(1.)
xarray.DataArray
  • 1.0
    array(1.)

Calculate the weighted quantile:

weighted_prec.quantile(q=0.5, dim="month")
<xarray.DataArray ()> Size: 8B
array(1.)
Coordinates:
 quantile float64 8B 0.5
xarray.DataArray
  • 1.0
    array(1.)
    • quantile
      ()
      float64
      0.5
      array(0.5)

The weighted sum corresponds to:

weighted_sum = (prec * weights).sum()
weighted_sum
<xarray.DataArray ()> Size: 8B
array(90.)
xarray.DataArray
  • 90.0
    array(90.)

the weighted mean to:

weighted_mean = weighted_sum / weights.sum()
weighted_mean
<xarray.DataArray ()> Size: 8B
array(1.)
xarray.DataArray
  • 1.0
    array(1.)

the weighted variance to:

weighted_var = weighted_prec.sum_of_squares() / weights.sum()
weighted_var
<xarray.DataArray ()> Size: 8B
array(0.00688889)
xarray.DataArray
  • 0.006889
    array(0.00688889)

and the weighted standard deviation to:

weighted_std = np.sqrt(weighted_var)
weighted_std
<xarray.DataArray ()> Size: 8B
array(0.08299933)
xarray.DataArray
  • 0.083
    array(0.08299933)

However, the functions also take missing values in the data into account:

data = xr.DataArray([np.nan, 2, 4])
weights = xr.DataArray([8, 1, 1])
data.weighted(weights).mean()
<xarray.DataArray ()> Size: 8B
array(3.)
xarray.DataArray
  • 3.0
    array(3.)

Using (data * weights).sum() / weights.sum() would (incorrectly) result in 0.6.

If the weights add up to to 0, sum returns 0:

data = xr.DataArray([1.0, 1.0])
weights = xr.DataArray([-1.0, 1.0])
data.weighted(weights).sum()
<xarray.DataArray ()> Size: 8B
array(0.)
xarray.DataArray
  • 0.0
    array(0.)

and mean, std and var return nan:

data.weighted(weights).mean()
<xarray.DataArray ()> Size: 8B
array(nan)
xarray.DataArray
  • nan
    array(nan)

Note

weights must be a DataArray and cannot contain missing values. Missing values can be replaced manually by weights.fillna(0).

Coarsen large arrays#

DataArray and Dataset objects include a coarsen() and coarsen() methods. This supports block aggregation along multiple dimensions,

x = np.linspace(0, 10, 300)
t = pd.date_range("1999年12月15日", periods=364)
da = xr.DataArray(
 np.sin(x) * np.cos(np.linspace(0, 1, 364)[:, np.newaxis]),
 dims=["time", "x"],
 coords={"time": t, "x": x},
)
da
<xarray.DataArray (time: 364, x: 300)> Size: 874kB
array([[ 0. , 0.03343858, 0.06683976, ..., -0.48672119,
 -0.51565952, -0.54402111],
 [ 0. , 0.03343845, 0.06683951, ..., -0.48671934,
 -0.51565756, -0.54401905],
 [ 0. , 0.03343807, 0.06683875, ..., -0.4867138 ,
 -0.51565169, -0.54401285],
 ...,
 [ 0. , 0.0182217 , 0.03642301, ..., -0.26522911,
 -0.28099849, -0.29645358],
 [ 0. , 0.01814439, 0.03626848, ..., -0.26410385,
 -0.27980632, -0.29519584],
 [ 0. , 0.01806694, 0.03611368, ..., -0.26297658,
 -0.27861203, -0.29393586]], shape=(364, 300))
Coordinates:
 * time (time) datetime64[us] 3kB 1999年12月15日 1999年12月16日 ... 2000年12月12日
 * x (x) float64 2kB 0.0 0.03344 0.06689 0.1003 ... 9.9 9.933 9.967 10.0
xarray.DataArray
  • time: 364
  • x: 300
  • 0.0 0.03344 0.06684 0.1002 0.1334 ... -0.247 -0.263 -0.2786 -0.2939
    array([[ 0. , 0.03343858, 0.06683976, ..., -0.48672119,
     -0.51565952, -0.54402111],
     [ 0. , 0.03343845, 0.06683951, ..., -0.48671934,
     -0.51565756, -0.54401905],
     [ 0. , 0.03343807, 0.06683875, ..., -0.4867138 ,
     -0.51565169, -0.54401285],
     ...,
     [ 0. , 0.0182217 , 0.03642301, ..., -0.26522911,
     -0.28099849, -0.29645358],
     [ 0. , 0.01814439, 0.03626848, ..., -0.26410385,
     -0.27980632, -0.29519584],
     [ 0. , 0.01806694, 0.03611368, ..., -0.26297658,
     -0.27861203, -0.29393586]], shape=(364, 300))
    • time
      (time)
      datetime64[us]
      1999年12月15日 ... 2000年12月12日
      array(['1999年12月15日T00:00:00.000000', '1999年12月16日T00:00:00.000000',
       '1999年12月17日T00:00:00.000000', ..., '2000年12月10日T00:00:00.000000',
       '2000年12月11日T00:00:00.000000', '2000年12月12日T00:00:00.000000'],
       shape=(364,), dtype='datetime64[us]')
    • x
      (x)
      float64
      0.0 0.03344 0.06689 ... 9.967 10.0
      array([ 0. , 0.033445, 0.06689 , ..., 9.93311 , 9.966555, 10. ],
       shape=(300,))

In order to take a block mean for every 7 days along time dimension and every 2 points along x dimension,

da.coarsen(time=7, x=2).mean()
<xarray.DataArray (time: 52, x: 150)> Size: 62kB
array([[ 0.01671847, 0.08349886, 0.14990579, ..., -0.41198807,
 -0.47195655, -0.52981418],
 [ 0.01671269, 0.08347003, 0.14985403, ..., -0.41184582,
 -0.47179359, -0.52963124],
 [ 0.01670071, 0.08341016, 0.14974655, ..., -0.41155042,
 -0.47145519, -0.52925136],
 ...,
 [ 0.00968205, 0.04835611, 0.0868139 , ..., -0.23859177,
 -0.2733209 , -0.30682759],
 [ 0.00941742, 0.04703446, 0.08444113, ..., -0.23207067,
 -0.26585059, -0.29844148],
 [ 0.00914929, 0.04569531, 0.08203696, ..., -0.22546326,
 -0.25828142, -0.2899444 ]], shape=(52, 150))
Coordinates:
 * time (time) datetime64[us] 416B 1999年12月18日 1999年12月25日 ... 2000年12月09日
 * x (x) float64 1kB 0.01672 0.08361 0.1505 0.2174 ... 9.849 9.916 9.983
xarray.DataArray
  • time: 52
  • x: 150
  • 0.01672 0.0835 0.1499 0.2156 ... -0.1916 -0.2255 -0.2583 -0.2899
    array([[ 0.01671847, 0.08349886, 0.14990579, ..., -0.41198807,
     -0.47195655, -0.52981418],
     [ 0.01671269, 0.08347003, 0.14985403, ..., -0.41184582,
     -0.47179359, -0.52963124],
     [ 0.01670071, 0.08341016, 0.14974655, ..., -0.41155042,
     -0.47145519, -0.52925136],
     ...,
     [ 0.00968205, 0.04835611, 0.0868139 , ..., -0.23859177,
     -0.2733209 , -0.30682759],
     [ 0.00941742, 0.04703446, 0.08444113, ..., -0.23207067,
     -0.26585059, -0.29844148],
     [ 0.00914929, 0.04569531, 0.08203696, ..., -0.22546326,
     -0.25828142, -0.2899444 ]], shape=(52, 150))
    • time
      (time)
      datetime64[us]
      1999年12月18日 ... 2000年12月09日
      array(['1999年12月18日T00:00:00.000000', '1999年12月25日T00:00:00.000000',
       '2000年01月01日T00:00:00.000000', '2000年01月08日T00:00:00.000000',
       '2000年01月15日T00:00:00.000000', '2000年01月22日T00:00:00.000000',
       '2000年01月29日T00:00:00.000000', '2000年02月05日T00:00:00.000000',
       '2000年02月12日T00:00:00.000000', '2000年02月19日T00:00:00.000000',
       '2000年02月26日T00:00:00.000000', '2000年03月04日T00:00:00.000000',
       '2000年03月11日T00:00:00.000000', '2000年03月18日T00:00:00.000000',
       '2000年03月25日T00:00:00.000000', '2000年04月01日T00:00:00.000000',
       '2000年04月08日T00:00:00.000000', '2000年04月15日T00:00:00.000000',
       '2000年04月22日T00:00:00.000000', '2000年04月29日T00:00:00.000000',
       '2000年05月06日T00:00:00.000000', '2000年05月13日T00:00:00.000000',
       '2000年05月20日T00:00:00.000000', '2000年05月27日T00:00:00.000000',
       '2000年06月03日T00:00:00.000000', '2000年06月10日T00:00:00.000000',
       '2000年06月17日T00:00:00.000000', '2000年06月24日T00:00:00.000000',
       '2000年07月01日T00:00:00.000000', '2000年07月08日T00:00:00.000000',
       '2000年07月15日T00:00:00.000000', '2000年07月22日T00:00:00.000000',
       '2000年07月29日T00:00:00.000000', '2000年08月05日T00:00:00.000000',
       '2000年08月12日T00:00:00.000000', '2000年08月19日T00:00:00.000000',
       '2000年08月26日T00:00:00.000000', '2000年09月02日T00:00:00.000000',
       '2000年09月09日T00:00:00.000000', '2000年09月16日T00:00:00.000000',
       '2000年09月23日T00:00:00.000000', '2000年09月30日T00:00:00.000000',
       '2000年10月07日T00:00:00.000000', '2000年10月14日T00:00:00.000000',
       '2000年10月21日T00:00:00.000000', '2000年10月28日T00:00:00.000000',
       '2000年11月04日T00:00:00.000000', '2000年11月11日T00:00:00.000000',
       '2000年11月18日T00:00:00.000000', '2000年11月25日T00:00:00.000000',
       '2000年12月02日T00:00:00.000000', '2000年12月09日T00:00:00.000000'],
       dtype='datetime64[us]')
    • x
      (x)
      float64
      0.01672 0.08361 ... 9.916 9.983
      array([0.016722, 0.083612, 0.150502, 0.217391, 0.284281, 0.351171, 0.41806 ,
       0.48495 , 0.551839, 0.618729, 0.685619, 0.752508, 0.819398, 0.886288,
       0.953177, 1.020067, 1.086957, 1.153846, 1.220736, 1.287625, 1.354515,
       1.421405, 1.488294, 1.555184, 1.622074, 1.688963, 1.755853, 1.822742,
       1.889632, 1.956522, 2.023411, 2.090301, 2.157191, 2.22408 , 2.29097 ,
       2.35786 , 2.424749, 2.491639, 2.558528, 2.625418, 2.692308, 2.759197,
       2.826087, 2.892977, 2.959866, 3.026756, 3.093645, 3.160535, 3.227425,
       3.294314, 3.361204, 3.428094, 3.494983, 3.561873, 3.628763, 3.695652,
       3.762542, 3.829431, 3.896321, 3.963211, 4.0301 , 4.09699 , 4.16388 ,
       4.230769, 4.297659, 4.364548, 4.431438, 4.498328, 4.565217, 4.632107,
       4.698997, 4.765886, 4.832776, 4.899666, 4.966555, 5.033445, 5.100334,
       5.167224, 5.234114, 5.301003, 5.367893, 5.434783, 5.501672, 5.568562,
       5.635452, 5.702341, 5.769231, 5.83612 , 5.90301 , 5.9699 , 6.036789,
       6.103679, 6.170569, 6.237458, 6.304348, 6.371237, 6.438127, 6.505017,
       6.571906, 6.638796, 6.705686, 6.772575, 6.839465, 6.906355, 6.973244,
       7.040134, 7.107023, 7.173913, 7.240803, 7.307692, 7.374582, 7.441472,
       7.508361, 7.575251, 7.64214 , 7.70903 , 7.77592 , 7.842809, 7.909699,
       7.976589, 8.043478, 8.110368, 8.177258, 8.244147, 8.311037, 8.377926,
       8.444816, 8.511706, 8.578595, 8.645485, 8.712375, 8.779264, 8.846154,
       8.913043, 8.979933, 9.046823, 9.113712, 9.180602, 9.247492, 9.314381,
       9.381271, 9.448161, 9.51505 , 9.58194 , 9.648829, 9.715719, 9.782609,
       9.849498, 9.916388, 9.983278])

coarsen() raises a ValueError if the data length is not a multiple of the corresponding window size. You can choose boundary='trim' or boundary='pad' options for trimming the excess entries or padding nan to insufficient entries,

da.coarsen(time=30, x=2, boundary="trim").mean()
<xarray.DataArray (time: 12, x: 150)> Size: 14kB
array([[ 0.01670121, 0.08341265, 0.14975103, ..., -0.41156272,
 -0.47146929, -0.52926718],
 [ 0.0165891 , 0.08285275, 0.14874584, ..., -0.40880017,
 -0.46830462, -0.52571455],
 [ 0.01636376, 0.08172729, 0.14672529, ..., -0.40324704,
 -0.46194319, -0.51857326],
 ...,
 [ 0.01183847, 0.05912615, 0.10614938, ..., -0.29173175,
 -0.33419587, -0.37516528],
 [ 0.01082401, 0.05405954, 0.09705329, ..., -0.26673283,
 -0.30555813, -0.34301681],
 [ 0.00973567, 0.04862391, 0.08729468, ..., -0.23991312,
 -0.27483458, -0.30852683]], shape=(12, 150))
Coordinates:
 * time (time) datetime64[us] 96B 1999年12月29日T12:00:00 ... 2000年11月23日T12:...
 * x (x) float64 1kB 0.01672 0.08361 0.1505 0.2174 ... 9.849 9.916 9.983
xarray.DataArray
  • time: 12
  • x: 150
  • 0.0167 0.08341 0.1498 0.2154 ... -0.2039 -0.2399 -0.2748 -0.3085
    array([[ 0.01670121, 0.08341265, 0.14975103, ..., -0.41156272,
     -0.47146929, -0.52926718],
     [ 0.0165891 , 0.08285275, 0.14874584, ..., -0.40880017,
     -0.46830462, -0.52571455],
     [ 0.01636376, 0.08172729, 0.14672529, ..., -0.40324704,
     -0.46194319, -0.51857326],
     ...,
     [ 0.01183847, 0.05912615, 0.10614938, ..., -0.29173175,
     -0.33419587, -0.37516528],
     [ 0.01082401, 0.05405954, 0.09705329, ..., -0.26673283,
     -0.30555813, -0.34301681],
     [ 0.00973567, 0.04862391, 0.08729468, ..., -0.23991312,
     -0.27483458, -0.30852683]], shape=(12, 150))
    • time
      (time)
      datetime64[us]
      1999年12月29日T12:00:00 ... 2000-11-...
      array(['1999年12月29日T12:00:00.000000', '2000年01月28日T12:00:00.000000',
       '2000年02月27日T12:00:00.000000', '2000年03月28日T12:00:00.000000',
       '2000年04月27日T12:00:00.000000', '2000年05月27日T12:00:00.000000',
       '2000年06月26日T12:00:00.000000', '2000年07月26日T12:00:00.000000',
       '2000年08月25日T12:00:00.000000', '2000年09月24日T12:00:00.000000',
       '2000年10月24日T12:00:00.000000', '2000年11月23日T12:00:00.000000'],
       dtype='datetime64[us]')
    • x
      (x)
      float64
      0.01672 0.08361 ... 9.916 9.983
      array([0.016722, 0.083612, 0.150502, 0.217391, 0.284281, 0.351171, 0.41806 ,
       0.48495 , 0.551839, 0.618729, 0.685619, 0.752508, 0.819398, 0.886288,
       0.953177, 1.020067, 1.086957, 1.153846, 1.220736, 1.287625, 1.354515,
       1.421405, 1.488294, 1.555184, 1.622074, 1.688963, 1.755853, 1.822742,
       1.889632, 1.956522, 2.023411, 2.090301, 2.157191, 2.22408 , 2.29097 ,
       2.35786 , 2.424749, 2.491639, 2.558528, 2.625418, 2.692308, 2.759197,
       2.826087, 2.892977, 2.959866, 3.026756, 3.093645, 3.160535, 3.227425,
       3.294314, 3.361204, 3.428094, 3.494983, 3.561873, 3.628763, 3.695652,
       3.762542, 3.829431, 3.896321, 3.963211, 4.0301 , 4.09699 , 4.16388 ,
       4.230769, 4.297659, 4.364548, 4.431438, 4.498328, 4.565217, 4.632107,
       4.698997, 4.765886, 4.832776, 4.899666, 4.966555, 5.033445, 5.100334,
       5.167224, 5.234114, 5.301003, 5.367893, 5.434783, 5.501672, 5.568562,
       5.635452, 5.702341, 5.769231, 5.83612 , 5.90301 , 5.9699 , 6.036789,
       6.103679, 6.170569, 6.237458, 6.304348, 6.371237, 6.438127, 6.505017,
       6.571906, 6.638796, 6.705686, 6.772575, 6.839465, 6.906355, 6.973244,
       7.040134, 7.107023, 7.173913, 7.240803, 7.307692, 7.374582, 7.441472,
       7.508361, 7.575251, 7.64214 , 7.70903 , 7.77592 , 7.842809, 7.909699,
       7.976589, 8.043478, 8.110368, 8.177258, 8.244147, 8.311037, 8.377926,
       8.444816, 8.511706, 8.578595, 8.645485, 8.712375, 8.779264, 8.846154,
       8.913043, 8.979933, 9.046823, 9.113712, 9.180602, 9.247492, 9.314381,
       9.381271, 9.448161, 9.51505 , 9.58194 , 9.648829, 9.715719, 9.782609,
       9.849498, 9.916388, 9.983278])

If you want to apply a specific function to coordinate, you can pass the function or method name to coord_func option,

da.coarsen(time=7, x=2, coord_func={"time": "min"}).mean()
<xarray.DataArray (time: 52, x: 150)> Size: 62kB
array([[ 0.01671847, 0.08349886, 0.14990579, ..., -0.41198807,
 -0.47195655, -0.52981418],
 [ 0.01671269, 0.08347003, 0.14985403, ..., -0.41184582,
 -0.47179359, -0.52963124],
 [ 0.01670071, 0.08341016, 0.14974655, ..., -0.41155042,
 -0.47145519, -0.52925136],
 ...,
 [ 0.00968205, 0.04835611, 0.0868139 , ..., -0.23859177,
 -0.2733209 , -0.30682759],
 [ 0.00941742, 0.04703446, 0.08444113, ..., -0.23207067,
 -0.26585059, -0.29844148],
 [ 0.00914929, 0.04569531, 0.08203696, ..., -0.22546326,
 -0.25828142, -0.2899444 ]], shape=(52, 150))
Coordinates:
 * time (time) datetime64[us] 416B 1999年12月15日 1999年12月22日 ... 2000年12月06日
 * x (x) float64 1kB 0.01672 0.08361 0.1505 0.2174 ... 9.849 9.916 9.983
xarray.DataArray
  • time: 52
  • x: 150
  • 0.01672 0.0835 0.1499 0.2156 ... -0.1916 -0.2255 -0.2583 -0.2899
    array([[ 0.01671847, 0.08349886, 0.14990579, ..., -0.41198807,
     -0.47195655, -0.52981418],
     [ 0.01671269, 0.08347003, 0.14985403, ..., -0.41184582,
     -0.47179359, -0.52963124],
     [ 0.01670071, 0.08341016, 0.14974655, ..., -0.41155042,
     -0.47145519, -0.52925136],
     ...,
     [ 0.00968205, 0.04835611, 0.0868139 , ..., -0.23859177,
     -0.2733209 , -0.30682759],
     [ 0.00941742, 0.04703446, 0.08444113, ..., -0.23207067,
     -0.26585059, -0.29844148],
     [ 0.00914929, 0.04569531, 0.08203696, ..., -0.22546326,
     -0.25828142, -0.2899444 ]], shape=(52, 150))
    • time
      (time)
      datetime64[us]
      1999年12月15日 ... 2000年12月06日
      array(['1999年12月15日T00:00:00.000000', '1999年12月22日T00:00:00.000000',
       '1999年12月29日T00:00:00.000000', '2000年01月05日T00:00:00.000000',
       '2000年01月12日T00:00:00.000000', '2000年01月19日T00:00:00.000000',
       '2000年01月26日T00:00:00.000000', '2000年02月02日T00:00:00.000000',
       '2000年02月09日T00:00:00.000000', '2000年02月16日T00:00:00.000000',
       '2000年02月23日T00:00:00.000000', '2000年03月01日T00:00:00.000000',
       '2000年03月08日T00:00:00.000000', '2000年03月15日T00:00:00.000000',
       '2000年03月22日T00:00:00.000000', '2000年03月29日T00:00:00.000000',
       '2000年04月05日T00:00:00.000000', '2000年04月12日T00:00:00.000000',
       '2000年04月19日T00:00:00.000000', '2000年04月26日T00:00:00.000000',
       '2000年05月03日T00:00:00.000000', '2000年05月10日T00:00:00.000000',
       '2000年05月17日T00:00:00.000000', '2000年05月24日T00:00:00.000000',
       '2000年05月31日T00:00:00.000000', '2000年06月07日T00:00:00.000000',
       '2000年06月14日T00:00:00.000000', '2000年06月21日T00:00:00.000000',
       '2000年06月28日T00:00:00.000000', '2000年07月05日T00:00:00.000000',
       '2000年07月12日T00:00:00.000000', '2000年07月19日T00:00:00.000000',
       '2000年07月26日T00:00:00.000000', '2000年08月02日T00:00:00.000000',
       '2000年08月09日T00:00:00.000000', '2000年08月16日T00:00:00.000000',
       '2000年08月23日T00:00:00.000000', '2000年08月30日T00:00:00.000000',
       '2000年09月06日T00:00:00.000000', '2000年09月13日T00:00:00.000000',
       '2000年09月20日T00:00:00.000000', '2000年09月27日T00:00:00.000000',
       '2000年10月04日T00:00:00.000000', '2000年10月11日T00:00:00.000000',
       '2000年10月18日T00:00:00.000000', '2000年10月25日T00:00:00.000000',
       '2000年11月01日T00:00:00.000000', '2000年11月08日T00:00:00.000000',
       '2000年11月15日T00:00:00.000000', '2000年11月22日T00:00:00.000000',
       '2000年11月29日T00:00:00.000000', '2000年12月06日T00:00:00.000000'],
       dtype='datetime64[us]')
    • x
      (x)
      float64
      0.01672 0.08361 ... 9.916 9.983
      array([0.016722, 0.083612, 0.150502, 0.217391, 0.284281, 0.351171, 0.41806 ,
       0.48495 , 0.551839, 0.618729, 0.685619, 0.752508, 0.819398, 0.886288,
       0.953177, 1.020067, 1.086957, 1.153846, 1.220736, 1.287625, 1.354515,
       1.421405, 1.488294, 1.555184, 1.622074, 1.688963, 1.755853, 1.822742,
       1.889632, 1.956522, 2.023411, 2.090301, 2.157191, 2.22408 , 2.29097 ,
       2.35786 , 2.424749, 2.491639, 2.558528, 2.625418, 2.692308, 2.759197,
       2.826087, 2.892977, 2.959866, 3.026756, 3.093645, 3.160535, 3.227425,
       3.294314, 3.361204, 3.428094, 3.494983, 3.561873, 3.628763, 3.695652,
       3.762542, 3.829431, 3.896321, 3.963211, 4.0301 , 4.09699 , 4.16388 ,
       4.230769, 4.297659, 4.364548, 4.431438, 4.498328, 4.565217, 4.632107,
       4.698997, 4.765886, 4.832776, 4.899666, 4.966555, 5.033445, 5.100334,
       5.167224, 5.234114, 5.301003, 5.367893, 5.434783, 5.501672, 5.568562,
       5.635452, 5.702341, 5.769231, 5.83612 , 5.90301 , 5.9699 , 6.036789,
       6.103679, 6.170569, 6.237458, 6.304348, 6.371237, 6.438127, 6.505017,
       6.571906, 6.638796, 6.705686, 6.772575, 6.839465, 6.906355, 6.973244,
       7.040134, 7.107023, 7.173913, 7.240803, 7.307692, 7.374582, 7.441472,
       7.508361, 7.575251, 7.64214 , 7.70903 , 7.77592 , 7.842809, 7.909699,
       7.976589, 8.043478, 8.110368, 8.177258, 8.244147, 8.311037, 8.377926,
       8.444816, 8.511706, 8.578595, 8.645485, 8.712375, 8.779264, 8.846154,
       8.913043, 8.979933, 9.046823, 9.113712, 9.180602, 9.247492, 9.314381,
       9.381271, 9.448161, 9.51505 , 9.58194 , 9.648829, 9.715719, 9.782609,
       9.849498, 9.916388, 9.983278])

You can also use coarsen to reshape without applying a computation.

Computation using Coordinates#

Xarray objects have some handy methods for the computation with their coordinates. differentiate() computes derivatives by central finite differences using their coordinates,

a = xr.DataArray([0, 1, 2, 3], dims=["x"], coords=[[0.1, 0.11, 0.2, 0.3]])
a.differentiate("x")
<xarray.DataArray (x: 4)> Size: 32B
array([100. , 91.11111111, 10.58479532, 10. ])
Coordinates:
 * x (x) float64 32B 0.1 0.11 0.2 0.3
xarray.DataArray
  • x: 4
  • 100.0 91.11 10.58 10.0
    array([100. , 91.11111111, 10.58479532, 10. ])
    • x
      (x)
      float64
      0.1 0.11 0.2 0.3
      array([0.1 , 0.11, 0.2 , 0.3 ])

This method can be used also for multidimensional arrays,

a = xr.DataArray(
 np.arange(8).reshape(4, 2), dims=["x", "y"], coords={"x": [0.1, 0.11, 0.2, 0.3]}
)
a.differentiate("x")
<xarray.DataArray (x: 4, y: 2)> Size: 64B
array([[200. , 200. ],
 [182.22222222, 182.22222222],
 [ 21.16959064, 21.16959064],
 [ 20. , 20. ]])
Coordinates:
 * x (x) float64 32B 0.1 0.11 0.2 0.3
Dimensions without coordinates: y
xarray.DataArray
  • x: 4
  • y: 2
  • 200.0 200.0 182.2 182.2 21.17 21.17 20.0 20.0
    array([[200. , 200. ],
     [182.22222222, 182.22222222],
     [ 21.16959064, 21.16959064],
     [ 20. , 20. ]])
    • x
      (x)
      float64
      0.1 0.11 0.2 0.3
      array([0.1 , 0.11, 0.2 , 0.3 ])

integrate() computes integration based on trapezoidal rule using their coordinates,

a.integrate("x")
<xarray.DataArray (y: 2)> Size: 16B
array([0.78, 0.98])
Dimensions without coordinates: y
xarray.DataArray
  • y: 2
  • 0.78 0.98
    array([0.78, 0.98])

Note

These methods are limited to simple cartesian geometry. Differentiation and integration along multidimensional coordinate are not supported.

Fitting polynomials#

Xarray objects provide an interface for performing linear or polynomial regressions using the least-squares method. polyfit() computes the best fitting coefficients along a given dimension and for a given order,

x = xr.DataArray(np.arange(10), dims=["x"], name="x")
a = xr.DataArray(3 + 4 * x, dims=["x"], coords={"x": x})
out = a.polyfit(dim="x", deg=1, full=True)
out
<xarray.Dataset> Size: 64B
Dimensions: (degree: 2)
Coordinates:
 * degree (degree) int64 16B 1 0
Data variables:
 x_matrix_rank int64 8B 2
 x_singular_values (degree) float64 16B 1.358 0.3963
 polyfit_coefficients (degree) float64 16B 4.0 3.0
 polyfit_residuals float64 8B 4.522e-28
xarray.Dataset
    • degree: 2
    • degree
      (degree)
      int64
      1 0
      array([1, 0])
    • x_matrix_rank
      ()
      int64
      2
      array(2)
    • x_singular_values
      (degree)
      float64
      1.358 0.3963
      array([1.35754456, 0.39632407])
    • polyfit_coefficients
      (degree)
      float64
      4.0 3.0
      array([4., 3.])
    • polyfit_residuals
      ()
      float64
      4.522e-28
      array(4.52210772e-28)

The method outputs a dataset containing the coefficients (and more if full=True). The inverse operation is done with polyval(),

xr.polyval(coord=x, coeffs=out.polyfit_coefficients)
<xarray.DataArray (x: 10)> Size: 80B
array([ 3., 7., 11., 15., 19., 23., 27., 31., 35., 39.])
Dimensions without coordinates: x
xarray.DataArray
  • x: 10
  • 3.0 7.0 11.0 15.0 19.0 23.0 27.0 31.0 35.0 39.0
    array([ 3., 7., 11., 15., 19., 23., 27., 31., 35., 39.])

Note

These methods replicate the behaviour of numpy.polyfit() and numpy.polyval().

Fitting arbitrary functions#

Xarray objects also provide an interface for fitting more complex functions using scipy.optimize.curve_fit(). curvefit() accepts user-defined functions and can fit along multiple coordinates.

For example, we can fit a relationship between two DataArray objects, maintaining a unique fit at each spatial coordinate but aggregating over the time dimension:

defexponential(x, a, xc):
 return np.exp((x - xc) / a)
x = np.arange(-5, 5, 0.1)
t = np.arange(-5, 5, 0.1)
X, T = np.meshgrid(x, t)
Z1 = np.random.uniform(low=-5, high=5, size=X.shape)
Z2 = exponential(Z1, 3, X)
Z3 = exponential(Z1, 1, -X)
ds = xr.Dataset(
 data_vars=dict(
 var1=(["t", "x"], Z1), var2=(["t", "x"], Z2), var3=(["t", "x"], Z3)
 ),
 coords={"t": t, "x": x},
)
ds[["var2", "var3"]].curvefit(
 coords=ds.var1,
 func=exponential,
 reduce_dims="t",
 bounds={"a": (0.5, 5), "xc": (-5, 5)},
)
<xarray.Dataset> Size: 10kB
Dimensions: (x: 100, param: 2, cov_i: 2, cov_j: 2)
Coordinates:
 * x (x) float64 800B -5.0 -4.9 -4.8 ... 4.7 4.8 4.9
 * param (param) <U2 16B 'a' 'xc'
 * cov_i (cov_i) <U2 16B 'a' 'xc'
 * cov_j (cov_j) <U2 16B 'a' 'xc'
Data variables:
 var2_curvefit_coefficients (x, param) float64 2kB 3.0 -5.0 3.0 ... 3.0 4.9
 var2_curvefit_covariance (x, cov_i, cov_j) float64 3kB 9.286e-14 ... 1...
 var3_curvefit_coefficients (x, param) float64 2kB 0.9999 5.0 ... 1.0 -4.9
 var3_curvefit_covariance (x, cov_i, cov_j) float64 3kB 5.825e-11 ... 6...
xarray.Dataset
    • x: 100
    • param: 2
    • cov_i: 2
    • cov_j: 2
    • x
      (x)
      float64
      -5.0 -4.9 -4.8 -4.7 ... 4.7 4.8 4.9
      array([-5.000000e+00, -4.900000e+00, -4.800000e+00, -4.700000e+00,
       -4.600000e+00, -4.500000e+00, -4.400000e+00, -4.300000e+00,
       -4.200000e+00, -4.100000e+00, -4.000000e+00, -3.900000e+00,
       -3.800000e+00, -3.700000e+00, -3.600000e+00, -3.500000e+00,
       -3.400000e+00, -3.300000e+00, -3.200000e+00, -3.100000e+00,
       -3.000000e+00, -2.900000e+00, -2.800000e+00, -2.700000e+00,
       -2.600000e+00, -2.500000e+00, -2.400000e+00, -2.300000e+00,
       -2.200000e+00, -2.100000e+00, -2.000000e+00, -1.900000e+00,
       -1.800000e+00, -1.700000e+00, -1.600000e+00, -1.500000e+00,
       -1.400000e+00, -1.300000e+00, -1.200000e+00, -1.100000e+00,
       -1.000000e+00, -9.000000e-01, -8.000000e-01, -7.000000e-01,
       -6.000000e-01, -5.000000e-01, -4.000000e-01, -3.000000e-01,
       -2.000000e-01, -1.000000e-01, -1.776357e-14, 1.000000e-01,
       2.000000e-01, 3.000000e-01, 4.000000e-01, 5.000000e-01,
       6.000000e-01, 7.000000e-01, 8.000000e-01, 9.000000e-01,
       1.000000e+00, 1.100000e+00, 1.200000e+00, 1.300000e+00,
       1.400000e+00, 1.500000e+00, 1.600000e+00, 1.700000e+00,
       1.800000e+00, 1.900000e+00, 2.000000e+00, 2.100000e+00,
       2.200000e+00, 2.300000e+00, 2.400000e+00, 2.500000e+00,
       2.600000e+00, 2.700000e+00, 2.800000e+00, 2.900000e+00,
       3.000000e+00, 3.100000e+00, 3.200000e+00, 3.300000e+00,
       3.400000e+00, 3.500000e+00, 3.600000e+00, 3.700000e+00,
       3.800000e+00, 3.900000e+00, 4.000000e+00, 4.100000e+00,
       4.200000e+00, 4.300000e+00, 4.400000e+00, 4.500000e+00,
       4.600000e+00, 4.700000e+00, 4.800000e+00, 4.900000e+00])
    • param
      (param)
      <U2
      'a' 'xc'
      array(['a', 'xc'], dtype='<U2')
    • cov_i
      (cov_i)
      <U2
      'a' 'xc'
      array(['a', 'xc'], dtype='<U2')
    • cov_j
      (cov_j)
      <U2
      'a' 'xc'
      array(['a', 'xc'], dtype='<U2')
    • var2_curvefit_coefficients
      (x, param)
      float64
      3.0 -5.0 3.0 -4.9 ... 4.8 3.0 4.9
      array([[ 2.99999702e+00, -4.99999125e+00],
       [ 3.00000000e+00, -4.90000000e+00],
       [ 3.00000000e+00, -4.80000000e+00],
       [ 3.00000000e+00, -4.70000000e+00],
       [ 3.00000000e+00, -4.60000000e+00],
       [ 3.00000000e+00, -4.50000000e+00],
       [ 3.00000000e+00, -4.40000000e+00],
       [ 3.00000000e+00, -4.30000000e+00],
       [ 3.00000000e+00, -4.20000000e+00],
       [ 3.00000000e+00, -4.10000000e+00],
       [ 3.00000000e+00, -4.00000000e+00],
       [ 3.00000000e+00, -3.90000000e+00],
       [ 3.00000000e+00, -3.80000000e+00],
       [ 3.00000000e+00, -3.70000000e+00],
       [ 3.00000000e+00, -3.60000000e+00],
       [ 3.00000000e+00, -3.50000000e+00],
       [ 3.00000000e+00, -3.40000000e+00],
       [ 3.00000000e+00, -3.30000000e+00],
       [ 3.00000000e+00, -3.20000000e+00],
       [ 3.00000000e+00, -3.10000000e+00],
      ...
       [ 3.00000000e+00, 3.00000000e+00],
       [ 3.00000000e+00, 3.10000000e+00],
       [ 3.00000000e+00, 3.20000000e+00],
       [ 3.00000000e+00, 3.30000000e+00],
       [ 3.00000000e+00, 3.40000000e+00],
       [ 3.00000000e+00, 3.50000000e+00],
       [ 3.00000000e+00, 3.60000000e+00],
       [ 3.00000000e+00, 3.70000000e+00],
       [ 3.00000000e+00, 3.80000000e+00],
       [ 3.00000000e+00, 3.90000000e+00],
       [ 3.00000000e+00, 4.00000000e+00],
       [ 3.00000000e+00, 4.10000000e+00],
       [ 3.00000000e+00, 4.20000000e+00],
       [ 3.00000000e+00, 4.30000000e+00],
       [ 3.00000000e+00, 4.40000000e+00],
       [ 3.00000000e+00, 4.50000000e+00],
       [ 3.00000000e+00, 4.60000000e+00],
       [ 3.00000000e+00, 4.70000000e+00],
       [ 2.99999999e+00, 4.79999999e+00],
       [ 3.00000000e+00, 4.90000000e+00]])
    • var2_curvefit_covariance
      (x, cov_i, cov_j)
      float64
      9.286e-14 -2.66e-13 ... 1.104e-19
      array([[[ 9.28596932e-14, -2.65999839e-13],
       [-2.65999839e-13, 7.80679945e-13]],
       [[ 6.34332252e-27, -1.82094045e-26],
       [-1.82094045e-26, 5.34489715e-26]],
       [[ 3.98632605e-28, -1.09820156e-27],
       [-1.09820156e-27, 3.11125854e-27]],
       [[ 7.45073143e-23, -2.04184968e-22],
       [-2.04184968e-22, 5.76111545e-22]],
       [[ 0.00000000e+00, -0.00000000e+00],
       [-0.00000000e+00, 0.00000000e+00]],
       [[ 4.77784962e-28, -1.26078076e-27],
       [-1.26078076e-27, 3.45028182e-27]],
       [[ 4.40997802e-24, -1.09940948e-23],
       [-1.09940948e-23, 2.84871426e-23]],
      ...
       [[ 1.72720214e-19, 5.00452069e-20],
       [ 5.00452069e-20, 4.97021874e-20]],
       [[ 1.60432147e-28, 5.18191197e-29],
       [ 5.18191197e-29, 6.79389277e-29]],
       [[ 1.46019153e-24, 5.08294124e-25],
       [ 5.08294124e-25, 5.44774913e-25]],
       [[ 6.26558243e-20, 2.43610178e-20],
       [ 2.43610178e-20, 2.19691900e-20]],
       [[ 6.43900925e-28, 3.22751126e-28],
       [ 3.22751126e-28, 3.18675272e-28]],
       [[ 1.16101059e-18, 4.56239775e-19],
       [ 4.56239775e-19, 4.86794492e-19]],
       [[ 1.91825701e-19, 1.06339279e-19],
       [ 1.06339279e-19, 1.10353628e-19]]])
    • var3_curvefit_coefficients
      (x, param)
      float64
      0.9999 5.0 1.0 ... -4.8 1.0 -4.9
      array([[ 9.99943555e-01, 4.99994440e+00],
       [ 1.00000000e+00, 4.90000000e+00],
       [ 1.00000000e+00, 4.80000000e+00],
       [ 1.00000000e+00, 4.70000000e+00],
       [ 1.00000000e+00, 4.60000000e+00],
       [ 1.00000000e+00, 4.50000000e+00],
       [ 1.00000000e+00, 4.40000000e+00],
       [ 1.00000000e+00, 4.30000000e+00],
       [ 1.00000000e+00, 4.20000000e+00],
       [ 1.00000000e+00, 4.10000000e+00],
       [ 1.00000000e+00, 4.00000000e+00],
       [ 1.00000000e+00, 3.90000000e+00],
       [ 1.00000000e+00, 3.80000000e+00],
       [ 1.00000000e+00, 3.70000000e+00],
       [ 1.00000000e+00, 3.60000000e+00],
       [ 1.00000000e+00, 3.50000000e+00],
       [ 1.00000000e+00, 3.40000000e+00],
       [ 1.00000000e+00, 3.30000000e+00],
       [ 1.00000000e+00, 3.20000000e+00],
       [ 1.00000000e+00, 3.10000000e+00],
      ...
       [ 1.00000000e+00, -3.00000000e+00],
       [ 1.00000000e+00, -3.10000000e+00],
       [ 1.00000000e+00, -3.20000000e+00],
       [ 1.00000000e+00, -3.30000000e+00],
       [ 1.00000000e+00, -3.40000000e+00],
       [ 1.00000000e+00, -3.50000000e+00],
       [ 1.00000000e+00, -3.60000000e+00],
       [ 1.00000000e+00, -3.70000000e+00],
       [ 1.00000000e+00, -3.80000000e+00],
       [ 1.00000000e+00, -3.90000000e+00],
       [ 1.00000000e+00, -4.00000000e+00],
       [ 1.00000000e+00, -4.10000000e+00],
       [ 1.00000000e+00, -4.20000000e+00],
       [ 1.00000000e+00, -4.30000000e+00],
       [ 1.00000000e+00, -4.40000000e+00],
       [ 1.00000000e+00, -4.50000000e+00],
       [ 1.00000000e+00, -4.60000000e+00],
       [ 1.00000000e+00, -4.70000000e+00],
       [ 1.00000000e+00, -4.80000000e+00],
       [ 1.00000000e+00, -4.90000000e+00]])
    • var3_curvefit_covariance
      (x, cov_i, cov_j)
      float64
      5.825e-11 3.202e-11 ... 6.344e-30
      array([[[ 5.82523300e-11, 3.20201277e-11],
       [ 3.20201277e-11, 3.15385434e-11]],
       [[ 2.84263406e-27, 9.75076267e-28],
       [ 9.75076267e-28, 1.10214134e-27]],
       [[ 6.93878849e-21, 3.30721481e-21],
       [ 3.30721481e-21, 3.23075198e-21]],
       [[ 6.10927908e-23, 1.65742453e-23],
       [ 1.65742453e-23, 1.71179583e-23]],
       [[ 4.84246634e-23, 8.58142943e-24],
       [ 8.58142943e-24, 1.02520363e-23]],
       [[ 0.00000000e+00, -0.00000000e+00],
       [-0.00000000e+00, 0.00000000e+00]],
       [[ 1.04973826e-24, 1.10693133e-25],
       [ 1.10693133e-25, 4.39671952e-25]],
      ...
       [[ 6.42709869e-32, -5.58641723e-31],
       [-5.58641723e-31, 4.87553613e-30]],
       [[ 9.52293200e-32, -8.63966307e-31],
       [-8.63966307e-31, 7.85954240e-30]],
       [[ 0.00000000e+00, -0.00000000e+00],
       [-0.00000000e+00, 0.00000000e+00]],
       [[ 5.14143427e-32, -4.61467025e-31],
       [-4.61467025e-31, 4.15782051e-30]],
       [[ 5.61123982e-32, -5.05995777e-31],
       [-5.05995777e-31, 4.58286656e-30]],
       [[ 0.00000000e+00, -0.00000000e+00],
       [-0.00000000e+00, 0.00000000e+00]],
       [[ 7.54590625e-32, -6.91111165e-31],
       [-6.91111165e-31, 6.34419460e-30]]])

We can also fit multi-dimensional functions, and even use a wrapper function to simultaneously fit a summation of several functions, such as this field containing two gaussian peaks:

defgaussian_2d(coords, a, xc, yc, xalpha, yalpha):
 x, y = coords
 z = a * np.exp(
 -np.square(x - xc) / 2 / np.square(xalpha)
 - np.square(y - yc) / 2 / np.square(yalpha)
 )
 return z
defmulti_peak(coords, *args):
 z = np.zeros(coords[0].shape)
 for i in range(len(args) // 5):
 z += gaussian_2d(coords, *args[i * 5 : i * 5 + 5])
 return z
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
X, Y = np.meshgrid(x, y)
n_peaks = 2
names = ["a", "xc", "yc", "xalpha", "yalpha"]
names = [f"{name}{i}" for i in range(n_peaks) for name in names]
Z = gaussian_2d((X, Y), 3, 1, 1, 2, 1) + gaussian_2d((X, Y), 2, -1, -2, 1, 1)
Z += np.random.normal(scale=0.1, size=Z.shape)
da = xr.DataArray(Z, dims=["y", "x"], coords={"y": y, "x": x})
da.curvefit(
 coords=["x", "y"],
 func=multi_peak,
 param_names=names,
 kwargs={"maxfev": 10000},
)
<xarray.Dataset> Size: 2kB
Dimensions: (param: 10, cov_i: 10, cov_j: 10)
Coordinates:
 * param (param) <U7 280B 'a0' 'xc0' ... 'xalpha1' 'yalpha1'
 * cov_i (cov_i) <U7 280B 'a0' 'xc0' ... 'xalpha1' 'yalpha1'
 * cov_j (cov_j) <U7 280B 'a0' 'xc0' ... 'xalpha1' 'yalpha1'
Data variables:
 curvefit_coefficients (param) float64 80B -2.697 0.5361 ... 2.083 2.324
 curvefit_covariance (cov_i, cov_j) float64 800B 0.1276 ... 0.004645
xarray.Dataset
    • param: 10
    • cov_i: 10
    • cov_j: 10
    • param
      (param)
      <U7
      'a0' 'xc0' ... 'xalpha1' 'yalpha1'
      array(['a0', 'xc0', 'yc0', 'xalpha0', 'yalpha0', 'a1', 'xc1', 'yc1', 'xalpha1',
       'yalpha1'], dtype='<U7')
    • cov_i
      (cov_i)
      <U7
      'a0' 'xc0' ... 'xalpha1' 'yalpha1'
      array(['a0', 'xc0', 'yc0', 'xalpha0', 'yalpha0', 'a1', 'xc1', 'yc1', 'xalpha1',
       'yalpha1'], dtype='<U7')
    • cov_j
      (cov_j)
      <U7
      'a0' 'xc0' ... 'xalpha1' 'yalpha1'
      array(['a0', 'xc0', 'yc0', 'xalpha0', 'yalpha0', 'a1', 'xc1', 'yc1', 'xalpha1',
       'yalpha1'], dtype='<U7')
    • curvefit_coefficients
      (param)
      float64
      -2.697 0.5361 3.423 ... 2.083 2.324
      array([-2.69658897, 0.53605704, 3.42345262, 2.09486358, -1.18601953,
       3.21722543, 0.64685781, 2.08207605, 2.08319858, 2.3236518 ])
    • curvefit_covariance
      (cov_i, cov_j)
      float64
      0.1276 -0.005523 ... 0.004645
      array([[ 1.27648429e-01, -5.52284946e-03, -1.41335649e-02,
       7.15096535e-04, 2.24609256e-02, -8.08374200e-02,
       4.30006605e-04, -7.56290098e-02, 7.72294423e-05,
       -2.32259812e-02],
       [-5.52284946e-03, 6.67838730e-04, 6.23938950e-04,
       -4.73344656e-06, -9.74023412e-04, 3.50431634e-03,
       1.82560375e-04, 3.29603433e-03, -1.77695303e-06,
       1.02010771e-03],
       [-1.41335649e-02, 6.23938950e-04, 1.82524205e-03,
       -4.82307241e-05, -2.44810968e-03, 8.66563123e-03,
       -3.64140430e-05, 8.57023728e-03, 5.08139143e-06,
       2.84454160e-03],
       [ 7.15096535e-04, -4.73344656e-06, -4.82307241e-05,
       4.55131467e-04, 7.53256798e-05, -4.32162291e-04,
       1.98918416e-05, -2.54850132e-04, 2.12782023e-04,
       -7.88613451e-05],
       [ 2.24609256e-02, -9.74023412e-04, -2.44810968e-03,
       7.53256798e-05, 4.12942107e-03, -1.44523811e-02,
       8.03145256e-05, -1.33085031e-02, -1.10342982e-05,
       -4.01556733e-03],
       [-8.08374200e-02, 3.50431634e-03, 8.66563123e-03,
       -4.32162291e-04, -1.44523811e-02, 5.18520716e-02,
       -2.81786105e-04, 4.76961650e-02, -8.61829636e-05,
       1.43071321e-02],
       [ 4.30006605e-04, 1.82560375e-04, -3.64140430e-05,
       1.98918416e-05, 8.03145256e-05, -2.81786105e-04,
       1.55535873e-04, -2.38462508e-04, 5.69858105e-06,
       -6.42031199e-05],
       [-7.56290098e-02, 3.29603433e-03, 8.57023728e-03,
       -2.54850132e-04, -1.33085031e-02, 4.76961650e-02,
       -2.38462508e-04, 4.51051264e-02, 3.29360303e-05,
       1.40108956e-02],
       [ 7.72294423e-05, -1.77695303e-06, 5.08139143e-06,
       2.12782023e-04, -1.10342982e-05, -8.61829636e-05,
       5.69858105e-06, 3.29360303e-05, 1.64078655e-04,
       8.92476764e-06],
       [-2.32259812e-02, 1.02010771e-03, 2.84454160e-03,
       -7.88613451e-05, -4.01556733e-03, 1.43071321e-02,
       -6.42031199e-05, 1.40108956e-02, 8.92476764e-06,
       4.64470565e-03]])

Note

This method replicates the behavior of scipy.optimize.curve_fit().

Broadcasting by dimension name#

DataArray objects 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 numpy.reshape() or numpy.newaxis.

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

a = xr.DataArray([1, 2], [("x", ["a", "b"])])
a
<xarray.DataArray (x: 2)> Size: 16B
array([1, 2])
Coordinates:
 * x (x) <U1 8B 'a' 'b'
xarray.DataArray
  • x: 2
  • 1 2
    array([1, 2])
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')
b = xr.DataArray([-1, -2, -3], [("y", [10, 20, 30])])
b
<xarray.DataArray (y: 3)> Size: 24B
array([-1, -2, -3])
Coordinates:
 * y (y) int64 24B 10 20 30
xarray.DataArray
  • y: 3
  • -1 -2 -3
    array([-1, -2, -3])
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])

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

a * b
<xarray.DataArray (x: 2, y: 3)> Size: 48B
array([[-1, -2, -3],
 [-2, -4, -6]])
Coordinates:
 * x (x) <U1 8B 'a' 'b'
 * y (y) int64 24B 10 20 30
xarray.DataArray
  • x: 2
  • y: 3
  • -1 -2 -3 -2 -4 -6
    array([[-1, -2, -3],
     [-2, -4, -6]])
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])

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

c = xr.DataArray(np.arange(6).reshape(3, 2), [b["y"], a["x"]])
c
<xarray.DataArray (y: 3, x: 2)> Size: 48B
array([[0, 1],
 [2, 3],
 [4, 5]])
Coordinates:
 * y (y) int64 24B 10 20 30
 * x (x) <U1 8B 'a' 'b'
xarray.DataArray
  • y: 3
  • x: 2
  • 0 1 2 3 4 5
    array([[0, 1],
     [2, 3],
     [4, 5]])
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')
a + c
<xarray.DataArray (x: 2, y: 3)> Size: 48B
array([[1, 3, 5],
 [3, 5, 7]])
Coordinates:
 * x (x) <U1 8B 'a' 'b'
 * y (y) int64 24B 10 20 30
xarray.DataArray
  • x: 2
  • y: 3
  • 1 3 5 3 5 7
    array([[1, 3, 5],
     [3, 5, 7]])
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])

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

c - c.T
<xarray.DataArray (y: 3, x: 2)> Size: 48B
array([[0, 0],
 [0, 0],
 [0, 0]])
Coordinates:
 * y (y) int64 24B 10 20 30
 * x (x) <U1 8B 'a' 'b'
xarray.DataArray
  • y: 3
  • x: 2
  • 0 0 0 0 0 0
    array([[0, 0],
     [0, 0],
     [0, 0]])
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')

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

a2, b2 = xr.broadcast(a, b)
a2
<xarray.DataArray (x: 2, y: 3)> Size: 48B
array([[1, 1, 1],
 [2, 2, 2]])
Coordinates:
 * x (x) <U1 8B 'a' 'b'
 * y (y) int64 24B 10 20 30
xarray.DataArray
  • x: 2
  • y: 3
  • 1 1 1 2 2 2
    array([[1, 1, 1],
     [2, 2, 2]])
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])
b2
<xarray.DataArray (x: 2, y: 3)> Size: 48B
array([[-1, -2, -3],
 [-1, -2, -3]])
Coordinates:
 * x (x) <U1 8B 'a' 'b'
 * y (y) int64 24B 10 20 30
xarray.DataArray
  • x: 2
  • y: 3
  • -1 -2 -3 -1 -2 -3
    array([[-1, -2, -3],
     [-1, -2, -3]])
    • x
      (x)
      <U1
      'a' 'b'
      array(['a', 'b'], dtype='<U1')
    • y
      (y)
      int64
      10 20 30
      array([10, 20, 30])

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:

arr = xr.DataArray(np.arange(3), [("x", range(3))])
arr + arr[:-1]
<xarray.DataArray (x: 2)> Size: 16B
array([0, 2])
Coordinates:
 * x (x) int64 16B 0 1
xarray.DataArray
  • x: 2
  • 0 2
    array([0, 2])
    • x
      (x)
      int64
      0 1
      array([0, 1])

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

arr + xr.DataArray([1, 2], dims="x")
AlignmentError: cannot reindex or align along dimension 'x' because of conflicting dimension sizes: {2, 3} (note: an index is found along that dimension with size=3)

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

with xr.set_options(arithmetic_join="outer"):
 arr + arr[:1]
arr + arr[:1]
<xarray.DataArray (x: 1)> Size: 8B
array([0])
Coordinates:
 * x (x) int64 8B 0
xarray.DataArray
  • x: 1
  • 0
    array([0])
    • x
      (x)
      int64
      0
      array([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:

arr[0]
<xarray.DataArray ()> Size: 8B
array(0)
Coordinates:
 x int64 8B 0
xarray.DataArray
  • 0
    array(0)
    • x
      ()
      int64
      0
      array(0)
arr[1]
<xarray.DataArray ()> Size: 8B
array(1)
Coordinates:
 x int64 8B 1
xarray.DataArray
  • 1
    array(1)
    • x
      ()
      int64
      1
      array(1)
# notice that the scalar coordinate 'x' is silently dropped
arr[1] - arr[0]
<xarray.DataArray ()> Size: 8B
array(1)
xarray.DataArray
  • 1
    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
arr[0] + 1
<xarray.DataArray ()> Size: 8B
array(1)
Coordinates:
 x int64 8B 0
xarray.DataArray
  • 1
    array(1)
    • x
      ()
      int64
      0
      array(0)
# both arguments have the same 'x' coordinate
arr[0] - arr[0]
<xarray.DataArray ()> Size: 8B
array(0)
Coordinates:
 x int64 8B 0
xarray.DataArray
  • 0
    array(0)
    • x
      ()
      int64
      0
      array(0)

Math with datasets#

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

ds = xr.Dataset(
 {
 "x_and_y": (("x", "y"), np.random.randn(3, 5)),
 "x_only": ("x", np.random.randn(3)),
 },
 coords=arr.coords,
)
ds > 0
<xarray.Dataset> Size: 42B
Dimensions: (x: 3, y: 5)
Coordinates:
 * x (x) int64 24B 0 1 2
Dimensions without coordinates: y
Data variables:
 x_and_y (x, y) bool 15B True True False True ... True False False False
 x_only (x) bool 3B False True False
xarray.Dataset
    • x: 3
    • y: 5
    • x
      (x)
      int64
      0 1 2
      array([0, 1, 2])
    • x_and_y
      (x, y)
      bool
      True True False ... False False
      array([[ True, True, False, True, False],
       [False, False, False, True, True],
       [False, True, False, False, False]])
    • x_only
      (x)
      bool
      False True False
      array([False, True, False])

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

ds.mean(dim="x")
<xarray.Dataset> Size: 48B
Dimensions: (y: 5)
Dimensions without coordinates: y
Data variables:
 x_and_y (y) float64 40B -0.1779 0.449 -0.6525 0.2515 0.09179
 x_only float64 8B -0.371
xarray.Dataset
    • y: 5
    • x_and_y
      (y)
      float64
      -0.1779 0.449 ... 0.2515 0.09179
      array([-0.17785609, 0.44898802, -0.65254903, 0.25154093, 0.0917901 ])
    • x_only
      ()
      float64
      -0.371
      array(-0.37104797)
abs(ds)
<xarray.Dataset> Size: 168B
Dimensions: (x: 3, y: 5)
Coordinates:
 * x (x) int64 24B 0 1 2
Dimensions without coordinates: y
Data variables:
 x_and_y (x, y) float64 120B 0.4281 0.9399 0.884 ... 0.7523 0.1212 0.3989
 x_only (x) float64 24B 0.5093 0.2509 0.8548
xarray.Dataset
    • x: 3
    • y: 5
    • x
      (x)
      int64
      0 1 2
      array([0, 1, 2])
    • x_and_y
      (x, y)
      float64
      0.4281 0.9399 ... 0.1212 0.3989
      array([[0.42814595, 0.93994217, 0.88396705, 0.32287959, 0.349192 ],
       [0.26065527, 0.71054048, 0.32134873, 0.55295552, 1.02347863],
       [0.70105895, 1.11756237, 0.7523313 , 0.12121234, 0.39891634]])
    • x_only
      (x)
      float64
      0.5093 0.2509 0.8548
      array([0.5092711 , 0.25090334, 0.85477617])

Datasets also support NumPy ufuncs (requires NumPy v1.13 or newer), or alternatively you can use map() to map a function to each variable in a dataset:

np.sin(ds) # equivalent to ds.map(np.sin)
<xarray.Dataset> Size: 168B
Dimensions: (x: 3, y: 5)
Coordinates:
 * x (x) int64 24B 0 1 2
Dimensions without coordinates: y
Data variables:
 x_and_y (x, y) float64 120B 0.4152 0.8075 -0.7733 ... -0.1209 -0.3884
 x_only (x) float64 24B -0.4875 0.2483 -0.7544
xarray.Dataset
    • x: 3
    • y: 5
    • x
      (x)
      int64
      0 1 2
      array([0, 1, 2])
    • x_and_y
      (x, y)
      float64
      0.4152 0.8075 ... -0.1209 -0.3884
      array([[ 0.41518482, 0.80752399, -0.77326042, 0.31729866, -0.34213868],
       [-0.25771374, -0.65224356, -0.31584654, 0.5252046 , 0.85392346],
       [-0.64502725, 0.89903574, -0.6833427 , -0.12091574, -0.38842 ]])
    • x_only
      (x)
      float64
      -0.4875 0.2483 -0.7544
      array([-0.48754097, 0.24827912, -0.75442401])

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

ds + arr
<xarray.Dataset> Size: 168B
Dimensions: (x: 3, y: 5)
Coordinates:
 * x (x) int64 24B 0 1 2
Dimensions without coordinates: y
Data variables:
 x_and_y (x, y) float64 120B 0.4281 0.9399 -0.884 ... 1.248 1.879 1.601
 x_only (x) float64 24B -0.5093 1.251 1.145
xarray.Dataset
    • x: 3
    • y: 5
    • x
      (x)
      int64
      0 1 2
      array([0, 1, 2])
    • x_and_y
      (x, y)
      float64
      0.4281 0.9399 ... 1.879 1.601
      array([[ 0.42814595, 0.93994217, -0.88396705, 0.32287959, -0.349192 ],
       [ 0.73934473, 0.28945952, 0.67865127, 1.55295552, 2.02347863],
       [ 1.29894105, 3.11756237, 1.2476687 , 1.87878766, 1.60108366]])
    • x_only
      (x)
      float64
      -0.5093 1.251 1.145
      array([-0.5092711 , 1.25090334, 1.14522383])

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

ds2 = xr.Dataset({"x_and_y": 0, "x_only": 100})
ds - ds2
<xarray.Dataset> Size: 168B
Dimensions: (x: 3, y: 5)
Coordinates:
 * x (x) int64 24B 0 1 2
Dimensions without coordinates: y
Data variables:
 x_and_y (x, y) float64 120B 0.4281 0.9399 -0.884 ... -0.1212 -0.3989
 x_only (x) float64 24B -100.5 -99.75 -100.9
xarray.Dataset
    • x: 3
    • y: 5
    • x
      (x)
      int64
      0 1 2
      array([0, 1, 2])
    • x_and_y
      (x, y)
      float64
      0.4281 0.9399 ... -0.1212 -0.3989
      array([[ 0.42814595, 0.93994217, -0.88396705, 0.32287959, -0.349192 ],
       [-0.26065527, -0.71054048, -0.32134873, 0.55295552, 1.02347863],
       [-0.70105895, 1.11756237, -0.7523313 , -0.12121234, -0.39891634]])
    • x_only
      (x)
      float64
      -100.5 -99.75 -100.9
      array([-100.5092711 , -99.74909666, -100.85477617])

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

Wrapping custom computation#

It doesn’t always make sense to do computation directly with xarray objects:

  • In the inner loop of performance limited code, using xarray can add considerable overhead compared to using NumPy or native Python types. This is particularly true when working with scalars or small arrays (less than ~1e6 elements). Keeping track of labels and ensuring their consistency adds overhead, and xarray’s core itself is not especially fast, because it’s written in Python rather than a compiled language like C. Also, xarray’s high level label-based APIs removes low-level control over how operations are implemented.

  • Even if speed doesn’t matter, it can be important to wrap existing code, or to support alternative interfaces that don’t use xarray objects.

For these reasons, it is often well-advised to write low-level routines that work with NumPy arrays, and to wrap these routines to work with xarray objects. However, adding support for labels on both Dataset and DataArray can be a bit of a chore.

To make this easier, xarray supplies the apply_ufunc() helper function, designed for wrapping functions that support broadcasting and vectorization on unlabeled arrays in the style of a NumPy universal function ("ufunc" for short). apply_ufunc takes care of everything needed for an idiomatic xarray wrapper, including alignment, broadcasting, looping over Dataset variables (if needed), and merging of coordinates. In fact, many internal xarray functions/methods are written using apply_ufunc.

Simple functions that act independently on each value should work without any additional arguments:

squared_error = lambda x, y: (x - y) ** 2
arr1 = xr.DataArray([0, 1, 2, 3], dims="x")
xr.apply_ufunc(squared_error, arr1, 1)
<xarray.DataArray (x: 4)> Size: 32B
array([1, 0, 1, 4])
Dimensions without coordinates: x
xarray.DataArray
  • x: 4
  • 1 0 1 4
    array([1, 0, 1, 4])

For using more complex operations that consider some array values collectively, it’s important to understand the idea of "core dimensions" from NumPy’s generalized ufuncs. Core dimensions are defined as dimensions that should not be broadcast over. Usually, they correspond to the fundamental dimensions over which an operation is defined, e.g., the summed axis in np.sum. A good clue that core dimensions are needed is the presence of an axis argument on the corresponding NumPy function.

With apply_ufunc, core dimensions are recognized by name, and then moved to the last dimension of any input arguments before applying the given function. This means that for functions that accept an axis argument, you usually need to set axis=-1. As an example, here is how we would wrap numpy.linalg.norm() to calculate the vector norm:

defvector_norm(x, dim, ord=None):
 return xr.apply_ufunc(
 np.linalg.norm, x, input_core_dims=[[dim]], kwargs={"ord": ord, "axis": -1}
 )
vector_norm(arr1, dim="x")
<xarray.DataArray ()> Size: 8B
array(3.74165739)
xarray.DataArray
  • 3.742
    array(3.74165739)

Because apply_ufunc follows a standard convention for ufuncs, it plays nicely with tools for building vectorized functions, like numpy.broadcast_arrays() and numpy.vectorize. For high performance needs, consider using Numba’s vectorize and guvectorize.

In addition to wrapping functions, apply_ufunc can automatically parallelize many functions when using dask by setting dask='parallelized'. See Parallelize custom functions with apply_ufunc and map_blocks for details.

apply_ufunc() also supports some advanced options for controlling alignment of variables and the form of the result. See the docstring for full details and more examples.