Hi Muru,
sorry that was my bad, I’ve made a mistake when adapting the solution from SO. I’ve fixed the notebook gist (see link above).
For corrected code to determine the wanted pixel see below. There are two changes. First, y/lat is the first dim of our 2d array. Second, we need to use .isel
to select from the given index. The SO solution worked since in that example x and y didn’t have coordinates and a zero-based index is used with .sel
.
lat = 50.0
lon = 10.0
# find nearest xy-grid point to a specific latlon-coordinate
abslat = np.abs(dsg.lat-lat)
abslon = np.abs(dsg.lon-lon)
c = np.maximum(abslon, abslat)
# Attention: y/lat is first dim, get
([yidx], [xidx]) = np.where(c == np.min(c))
# Select index location at the x/y dimension
# use isel as we select with index
point_ds = dsg.isel(x=xidx, y=yidx)
display(point_ds.RW)
<xarray.DataArray 'RW' ()>
array(1.1, dtype=float32)
Coordinates:
y float64 -4.326e+06
x float64 37.83
lon float64 9.994
lat float64 50.0
Attributes:
valid_min: 0
valid_max: 4095
standard_name: rainfall_rate
long_name: RW
unit: mm h-1
As you can see, the lon/lat coordinates are now giving back our selected values (“nearest”).