将xarray.Dataset变量重新分类为新变量

时间:2018-10-03 14:21:12

标签: python-xarray

我有一个xarray.Dataset:

<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

我需要将slc变量重新分类为一个名为“ cfmask”的新变量。

这是我需要应用的重分类规则:

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)]

在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

例如,要回答delgadom问题,我需要在新的“ cfmask”变量中将slc变量的类别0转换为类别255。 slc类别1进入cfmask类别255,...

我终于找到了使用以上两个资源的解决方案。我不知道这是否是最有效的方法。

来源:

Array reclassification with numpy

How can I replace values in an xarray variable?

我的解决方案:

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

然后我的问题中显示的原始xarray.Dataset(dataset_in)变为:

<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