user118967
user118967

Reputation: 5722

Accessing data in Python xarray by coordinate, not integer index

The following use of xarray would be intuitive to me, but does not work:

import xarray as xr
import numpy as np

data = xr.DataArray(np.random.randn(2, 3),
                    [
                         ("x", [10, 20]), 
                         ("y", [0, 1, 2])
                    ])

# x values are 10 and 20. Here I want to modify the value at x=10 and y=0:
data[dict(x=10, y=0)] = 1.0  # IndexError: index 10 is out of bounds for axis 0 with size 2
data[dict(x=0, y=0)] = 1.0  # Ok!

Is there a way to access the data using the coordinates (here, 10 and 20 for "x")?

Upvotes: 1

Views: 524

Answers (1)

Michael Delgado
Michael Delgado

Reputation: 15442

Yes there is!

You can use xr.DataArray.loc in exactly this way:

In [2]: data.loc[dict(x=10, y=0)] = 1.0

In [3]: data
Out[3]:
<xarray.DataArray (x: 2, y: 3)>
array([[ 1.        ,  2.76591321, -0.46252906],
       [-0.58849111, -1.3752737 ,  0.72525296]])
Coordinates:
  * x        (x) int64 10 20
  * y        (y) int64 0 1 2

Directly slicing the array, as in da[i, j] slices the array positionally, as in numpy. See the xarray docs on indexing and selecting data for more information and examples.

Upvotes: 1

Related Questions