简体   繁体   中英

Update individual value in an xarray DataArray in-place?

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.DataArray s 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM