cleanest way to modify a netcdf entry in xarray using nearest location and given time stamp

Viewed 24

I want to modify the value of a netcdf array at a given index which is the nearest array entry to my chosen lat/lon coordinate and for a given date. I came up with the following solution using xarray's sel and loc but the loc command seems very longwinded with all the "values", using the online xarray manual and also this answer

ds=xr.open_dataset("test1.nc")
idx=ds.sel(lon=0,lat=20,time="1951-03-15",method="nearest")
ds["sit"].loc[dict(lon=idx.coords["lon"].values,lat=idx.coords["lat"].values,time=idx.coords["time"].values)]=100
ds.to_netcdf("test2.nc")

Is there is a shorter, neater way to do this task?

1 Answers

You can pass DataArrays for the dictionary values to xr.DataArray.loc:

ds["sit"].loc[dict(lon=idx.lon,lat=idx.lat,time=idx.time)] = 100
Related