Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 943
Ben Avatar asked Jul 07 '26 03:07

Ben


2 Answers

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
like image 168
Val Avatar answered Jul 09 '26 16:07

Val


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
like image 22
Maximilian Avatar answered Jul 09 '26 17:07

Maximilian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!