Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the indices equivalent to a specific selection of xarray?

Tags:

I have an xarray dataset.

<xarray.Dataset>
Dimensions:           (lat: 92, lon: 172, time: 183)
Coordinates:
  * lat               (lat) float32 4.125001 4.375 4.625 ... 26.624994 26.874996
  * lon               (lon) float32 nan nan nan ... 24.374996 24.624998 24.875
  * time              (time) datetime64[ns] 2003-09-01 2003-09-02 ... 2004-03-01
Data variables:
    swnet        (time, lat, lon) float32 dask.array<shape=(183, 92, 172), chunksize=(1, 92, 172)>

Find the nearest lat-long

df.sel(time='2003-09-01', lon=6.374997, lat=16.375006, method='nearest')

Need to find

The indices of this particular location. Basically, the row-column in the grid. What would be the easiest way to go about it?

Tried

nearestlat=df.sel(time='2003-09-01', lon=6.374997, lat=16.375006, method='nearest')['lat'].values 
nearestlon=df.sel(time='2003-09-01', lon=6.374997, lat=16.375006, method='nearest')['lon'].values 
rowlat=np.where(df['lat'].values==nearestlat)[0][0] 
collon=np.where(df['lon'].values==nearestlon)[0][0] 

But I am not sure if this is the right way to go about it. How can I do this 'correctly'?

like image 342
maximusdooku Avatar asked Apr 27 '20 10:04

maximusdooku


1 Answers

I agree that finding the index associated with a .sel operation is trickier than one would expect!

This code works:

import xarray as xr
ds = xr.tutorial.open_dataset('air_temperature')
ilon = list(ds.lon.values).index(ds.sel(lon=250.0, method='nearest').lon)
ilat = list(ds.lat.values).index(ds.sel(lat=45.0, method='nearest').lat)
print(' lon index=',ilon,'\n','lat index=', ilat)

producing:

 lon index= 20 
 lat index= 12

And just in case one is wondering why one might want to do this, we use this for investigating time stacks of images, where we are interested in selecting the image immediately preceding the image on a specified date:

import xarray as xr
ds = xr.tutorial.open_dataset('air_temperature')
ilon = list(ds.time.values).index(ds.sel(time='2013-06-01 00:00:00', method='nearest').time)
print(idx)

which produces

848
like image 81
Rich Signell Avatar answered Sep 30 '22 20:09

Rich Signell