Perhaps it's poor form, but is there a way to update a single value of an xarray DataArray in-place? I am performing a trend analysis in which I subset each (lat, lon) cell and analyze over the time slice.
I want to be able to do something like:
output_array.loc[dict(lat=i, lon=j)]['intercept'] = intercept
or
output_array.sel(lat=i, lon=j)['intercept'] = intercept
In which intercept is a single value (float) to be updated in the output['intercept'] DataArray
xarray.DataArrays are basically wrappers around numpy ndarrays, which means you can just modify the underlying numpy array.
You can access (and modify) the array with either the .data or .values property.
import xarray as xr
# load testdata
x = xr.tutorial.load_dataset("air_temperature")
# keep second reference of array just for showcasing
arr = x.air.data
# it's the same
assert arr is x.air.data
# indices
i,j,k = (0,0,0)
print(x.air.data[i,j,k], arr[i,j,k])
# 241.2 241.2
# new value
x.air.data[i,j,k] = 0
# check
print(x.air.data[i,j,k], arr[i,j,k])
# 0.0 0.0
To add onto @val's excellent answer, it's possible to mutate the array directly, without needing to go through the .data attribute:
In [5]: x.air[i,j,k] = 0
In [6]: print(x.air.data[i,j,k], arr[i,j,k])
0.0 0.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With