'Xarray masking at certain location
I have a xarray data set and want to transform the values of my variable in a specific region within the dataset to Nan values. Using dataset.where I only get the specific region as the output but I want to keep the values at the locations around the mask in the array. So basically I want to keep my dataset but replace the values of my variable at certain coordinates with NaN.
[The dataset is called Lae21 and the lon/lat_mask are sliced coordinates from the dataset]
`print(Lae21)
mask = Lae21.where((Lae21.x!=lon_mask) & (Lae21.y!=lat_mask))
print(mask)`
<xarray.Dataset>
Dimensions: (y: 1614, x: 7682)
Coordinates:
* y (y) float64 5.261e+06 5.261e+06 5.261e+06 ... 5.256e+06 5.256e+06
* x (x) float64 4.389e+05 4.389e+05 4.389e+05 ... 4.619e+05 4.619e+05
Data variables:
NDVI (y, x) float32 ...
Attributes:
transform: (3.0, 0.0, 438857.72, 0.0, -3.0, 5260962.7)
crs: +init=epsg:32632
res: (3.0, 3.0)
is_tiled: 0
nodatavals: (nan,)
scales: (1.0,)
offsets: (0.0,)
AREA_OR_POINT: Area
TIFFTAG_XRESOLUTION: 1
TIFFTAG_YRESOLUTION: 1
<xarray.DataArray 'NDVI' (y: 3, x: 3)>
array([[nan, nan, nan],
[nan, nan, nan],
[nan, nan, nan]], dtype=float32)
Coordinates:
* y (y) float64 5.259e+06 5.259e+06 5.259e+06
* x (x) float64 4.521e+05 4.521e+05 4.521e+05
So the resulting array should be all the values from the original dataset Lae21 and NaN values at the specific location of the mask. (Looking at examples of the .where function I thought that should be the output...).
Thanks a lot for your answers!
Solution 1:[1]
I would use .loc method for this:
Lae21.NDVI.loc[{"x": lat_mask, "y": lon_mask}] = np.NaN
See this specific chapter of xarray indexing guide for more details.
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 | Abel |
