robintw
robintw

Reputation: 28531

Extract values at point locations from an xarray DataArray, and get all other values separately

I have an xarray DataArray as follows:

import xarray as xr
import numpy as np

da = xr.DataArray(np.arange(25).reshape(5, 5), dims=['x', 'y'], coords={'x': np.arange(5), 'y': np.arange(5)})

It looks like this:

DataArray

I want to select the values of the data array that are closest to some specific x, y point locations that I have.

To do this, I can put those point co-ordinates into DataArrays themselves, and index using those:

x_coords = xr.DataArray([1.2, 3.6, 4.9])
y_coords = xr.DataArray([2.2, 0.7, 4.3])

da.sel(x=x_coords, y=y_coords, method='nearest')

This gives the expected result of [7, 21, 24].

However, I now want to get the 'other' elements of the array. That is, the ones that are in cells that aren't the nearest cells to the point locations I gave. In this case, this would be all the numbers from 0 to 24 excluding 7, 21 and 24. However, in my real array the values are not unique like this.

How can I get these values?

I wondered if I could do something using sets, but I would need to treat the x and y co-ordinates together, as the co-ordinates come in pairs, and I couldn't work out how to do this.

If necessary, I'm happy with a numpy-only solution, but I'd prefer a pure xarray solution.

Upvotes: 2

Views: 2140

Answers (1)

Simon
Simon

Reputation: 2002

I also could not find a solution carried by the xarray library. A work around is to first use the interp function using the list of coordinates x and y. Then simply grab the diagonal of the output.

import numpy as np

val = np.diagonal(da.interp({'x':x_coords, 'y':y_coords}, method='linear').values[0,:,:])

print(val)

the array val will contain the interpolated values at the (x,y) coordinates

Upvotes: 0

Related Questions