Reputation: 145
I have got an xarray.Dataset as this one:
<xarray.Dataset>
Dimensions: (latitude: 881, longitude: 881, time: 152)
Coordinates:
* time (time) datetime64[ns] 2017-01-03T10:48:57 2017-01-07T10:33:06 ...
* latitude (latitude) float64 46.15 46.15 46.15 46.15 46.15 46.15 46.15 ...
* longitude (longitude) float64 7.5 7.5 7.5 7.5 7.501 7.501 7.501 7.501 ...
Data variables:
red (time, latitude, longitude) int16 -9999 -9999 -9999 -9999 ...
nir (time, latitude, longitude) int16 -9999 -9999 -9999 -9999 ...
slc (time, latitude, longitude) uint8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
Attributes:
crs: EPSG:4326
I need to relassify the slc variable into a new one called "cfmask".
Here is the reclassification rules I need to apply:
lookups = [(0,255), (1,255), (2,0), (3,2), (4,0), (5,0), (6,1), (7,255), (8,4), (9,4), (0,4), (11,3)]
Thanks in advance for any help.
Upvotes: 2
Views: 679
Reputation: 145
To answer delgadom question, for example I need to convert category 0 of slc variable into category 255 in a new "cfmask" variable. slc category 1 into cfmask category 255,...
I finally found a solution using the two sources above. I do not know if it is the most efficient way to do it.
The sources:
Array reclassification with numpy
How can I replace values in an xarray variable?
My solution:
lookups = [(0,255), (1,255), (2,0), (3,2), (4,0), (5,0), (6,1), (7,255), (8,4), (9,4), (10,4), (11,3)]
idx, val = np.asarray(lookups).T
lookup_array = np.zeros(idx.max() + 1)
lookup_array[idx] = val
cfmask = lookup_array[dataset_in.slc.values].astype(np.uint8)
cfmask = xr.DataArray(cfmask,
coords={'latitude': dataset_in['latitude'].values,
'longitude': dataset_in['longitude'].values,
'time': dataset_in['time'].values},
dims=['time', 'latitude', 'longitude'])
dataset_in['cfmask'] = cfmask
Then the original xarray.Dataset (dataset_in) presented in my question becomes:
<xarray.Dataset>
Dimensions: (latitude: 881, longitude: 881, time: 152)
Coordinates:
* time (time) datetime64[ns] 2017-01-03T10:48:57 2017-01-07T10:33:06 ...
* latitude (latitude) float64 46.15 46.15 46.15 46.15 46.15 46.15 46.15 ...
* longitude (longitude) float64 7.5 7.5 7.5 7.5 7.501 7.501 7.501 7.501 ...
Data variables:
red (time, latitude, longitude) int16 -9999 -9999 -9999 -9999 ...
nir (time, latitude, longitude) int16 -9999 -9999 -9999 -9999 ...
slc (time, latitude, longitude) uint8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
cfmask (time, latitude, longitude) uint8 255 255 255 255 255 255 255 ...
Attributes:
crs: EPSG:4326
Upvotes: 2