'Replacing a slice of data from a DataArray with a new array of data with the same shape
I have a xarray DataArray of wind speeds / wind directions with Lat/Lon coordinates and times stored in a dictionary (there are more than one, but for this we'll just deal with one of them). I am interested only in a specific area i.e lat0:lat1 and lon0:lon1 where I have changed some of the wind speed values using a model where I have a resulting 10x10 array of the new values. How can I replace only the slice of data with my new array?
I have tried using:
da[key]["wind_speed"].isel(time=0,lat=slice(lat0,lat1),lon=slice(lon0,lon1)).data = new_array
Also:
da[key].wind_speed[0,lat0:lat1,lon0:lon1].data = new_array
In both cases the types and shapes are the same of the data and arrays, however the DataArray will not be updated.
Is this a problem about me not replacing data in a DataArray properly or is this a problem with replacing a DataArray inside of a dictionary?
I would be grateful for any help!
Solution 1:[1]
You can replace values inside the xarray using .loc (as in pandas)
But, in this case you have to pass the coordinates, and you are using indices (isel).
For example, if you have this array with shape (3, 343, 343):

And you want to change the values of an square with 10 pxs on top left. You need the coordinates (x and y) for these pixels using isel, so:
area = img.isel(y=slice(0, 10), x=slice(0, 10))
Then you can assign the values using loc (assigning ones just for demonstration).
img.iloc[{'x': area.x, 'y': area.y}] = np.ones(area.shape)
img
array([[[ 1, 1, 1, ..., 88, 72, 0],
[ 1, 1, 1, ..., 32, 96, 0],
[ 1, 1, 1, ..., 41, 94, 0],
...,
[23, 47, 24, ..., 67, 23, 0],
[27, 20, 57, ..., 16, 12, 0],
[ 0, 0, 0, ..., 0, 0, 0]],
[[ 1, 1, 1, ..., 78, 61, 0],
[ 1, 1, 1, ..., 35, 76, 0],
[ 1, 1, 1, ..., 45, 77, 0],
...,
[45, 60, 35, ..., 67, 32, 0],
[38, 36, 65, ..., 26, 22, 0],
[ 0, 0, 0, ..., 0, 0, 0]],
[[ 1, 1, 1, ..., 47, 38, 0],
[ 1, 1, 1, ..., 23, 49, 0],
[ 1, 1, 1, ..., 23, 48, 0],
...,
[28, 34, 22, ..., 40, 16, 0],
[21, 21, 39, ..., 16, 10, 0],
[ 0, 0, 0, ..., 0, 0, 0]]], dtype=uint8)
...and the original array is modified accordingly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MaurĂcio Cordeiro |
