0

I want to use xr.where to get index: (time, lat, lon) which contain t<22 from let say this xarray dataset:

import xarray as xr
np.random.seed(0)
t = 15 + 8 * np.random.randn(2, 2, 3)
lon = [[-99.83, -99.32], [-99.79, -99.23]]
lat = [[42.25, 42.21], [42.63, 42.59]]
time = pd.date_range("2014-09-06", periods=3)
reference_time = pd.Timestamp("2014-09-05")
ds = xr.Dataset(
    data_vars=dict(
        t=(["x", "y", "time"], temperature),
    ),
    coords=dict(
        lon=(["x", "y"], lon),
        lat=(["x", "y"], lat),
        time=time,
        reference_time=reference_time,
    ),
    attrs=dict(description="Weather related data."),
)

I tried:

time, lat_i, lon_i = np.nonzero(xr.where(ds.t<22, 1, 0).data)
lats = ds.x.isel(x=lat_i).data
lons = ds.y.isel(y=lon_i).data
time = ds.time.isel(time=time).data
pairs = list(zip(time, lats, lons))
pairs

But got an error related to lons, IndexError: index 2 is out of bounds for axis 0 with size 2

print(time, lat_i, lon_i)
(array([0, 0, 1, 1, 1, 1], dtype=int64),
 array([0, 1, 0, 0, 1, 1], dtype=int64),
 array([1, 2, 1, 2, 0, 1], dtype=int64))

Why there is, not expected, 2 in the lon_i?

Michael Delgado
  • 13,789
  • 3
  • 29
  • 54
Tugiyo
  • 31
  • 6
  • Should be lat_i, lon_i, time = ... and 2 is for time? – Tugiyo Jan 05 '23 at 15:42
  • lat_i, lon_i, time = ... is correct order and finally no errors about 2 etc – Tugiyo Jan 06 '23 at 01:00
  • if you're selecting using labels (e.g. the values of `lon`, `lat`, and `time`) rather than positions, use [`.sel`](https://docs.xarray.dev/en/stable/generated/xarray.Dataset.sel.html), not [`.isel`](https://docs.xarray.dev/en/stable/generated/xarray.Dataset.isel.html). – Michael Delgado Jan 08 '23 at 04:10

0 Answers0