Home Articles

python-xarray从一个DataArray复制掩码到另一个

Asked
Viewed 1568 times
1

我让这个用于一个简单的案例:

arr2 = xr.DataArray((np.arange(16)-8).reshape(4, 4), dims=['x', 'y'])
arr3 = xr.DataArray(np.arange(16).reshape(4, 4), dims=['x', 'y'])
<xarray.DataArray (x: 4, y: 4)>
array([[ nan,  nan,  nan,  nan],
[ nan,  nan,  nan,  nan],
[ nan,   9.,  10.,  11.],
[ 12.,  13.,  14.,  15.]])
Dimensions without coordinates: x, y

但是,我在处理NetCDF文件时遇到了麻烦 . 我有两个数据集:有效波高(Hs)和风速(ws) . 我想使用Hs <0的掩码并将其应用于ws . 数据集的大小为[time = 1,lat = 81,lon = 131] . 在期货中会有一段时间,我的ws DataArray的大小会略有不同,例如: [时间= 1,ENS = 10,LAT = 81,LON = 131] .

如果我尝试:

f = xr.open_dataset('CCSM4_ens1_19821201_19831130_ws10_0_NAtl_DJFmean.nc')
ws10 = f.ws10
f = xr.open_dataset('ww3.Hs.19820901_19830831_NAtl_DJFmean.nc')
hs = f.hs
ws10_masked = ws10.where(hs > 0)

ws10_masked看起来像:

xarray.DataArray (time: 1, lat: 81, lon: 131, latitude: 81, longitude: 131)
array([[[[[ nan, ...,  nan],
      ..., 
      [ nan, ...,  nan]],
     ..., 
     [[ nan, ...,  nan],
      ..., 
      [ nan, ...,  nan]]],
      ..., 
      [[[ nan, ...,  nan],
      ..., 
      [ nan, ...,  nan]],
      ..., 
      [[ nan, ...,  nan],
      ..., 
      [ nan, ...,  nan]]]]])
Coordinates:
* lat        (lat) float64 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 ...
* lon        (lon) float64 260.0 261.0 262.0 263.0 264.0 265.0 266.0 267.0 ...
* time       (time) datetime64[ns] 1983-01-15T12:00:00
* latitude   (latitude) float32 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 ...
* longitude  (longitude) float32 -100.0 -99.0 -98.0 -97.0 -96.0 -95.0 
...
Attributes:
associated_files:  baseURL: http://cmip-
pcmdi.llnl.gov/CMIP5/dataLocation...
cell_methods:      time: mean
history:           2014-07-03T07:58:56Z altered by CMOR: Treated 
scalar d...
long_name:         Eastward Near-Surface Wind
standard_name:     eastward_wind
units:             m s-1

你可以看到因为ws有维度名称lon和lat,因为Hs具有维度名称经度和纬度,它创建了一个5维DataArray而没有正确选择掩码 .

无论尺寸名称是否不同,或者DataArrays的大小不同,我都能选择掩码吗?

我之前使用numpy.math(ma)执行此操作:

hs = f.variables['hs'][:]
hs_masked = ma.masked_values(hs, -65.534004)
tmp = np.zeros((len(lat), len(lon))
# Create masked array
data_cs = ma.masked_values(tmp, 0)
# Read new file
tmp = f.variables['cusp'][:]
data_cs[:,:] = ma.masked_array(tmp, hs_masked.mask)

但希望学习/使用xarray .

干杯,雷

1 Answer

  • 2

    您需要明确重命名要匹配的维名称,例如 hs = hs.rename({'lat': 'latitude', 'longitude': 'longitude'}) . 如果坐标标签不完全匹配,您可能还需要使用nearest-neighbor indexing重新索引,例如 hs.reindex_like(ws10, method='nearest', tolerance=0.01) .

    或者,不太安全,您可以从第二个参数中去除坐标标签,而只是传入一个未标记的数组,例如 ws10.where(hs.data > 0) . 但我不推荐这个选项,因为没有什么能保证元数据的一致性 .

Related