首页 > 解决方案 > 基于多个条件的 Xarray 掩码区域

问题描述

我正在查看一个全局 netcdf 文件。我想将 60-75 度 N 波段内的所有陆地点设置为零,但将该波段中的海洋点保持为 nan。作为第二步,我想将土地点的值保持在 60-75 之间,但将所有其他土地点设置为零。海洋值是 NaN。我只是没有让我的 xarray 脚本做到这一点 - 这是我尝试过的

import numpy as np
import matplotlib.pyplot as plt

ds = xr.open_dataset('ifle.nc')

ds['Shrub_total'] = ds['Shrub']

shrub_total = ds.Shrub_total

tundra = shrub_total.where((shrub_total!=np.nan)&(shrub_total.Lat>60)&
                           (shrub_total.Lat<75), 0)
shrub = shrub_total.where((shrub_total!=np.nan)&(shrub_total.Lat<60)&
                          (shrub_total.Lat>75), 0)

ds['Tundra'] = tundra
ds['Shrub'] = shrub

fig, axes = plt.subplots(ncols=2,figsize=(12,3))

ds['Shrub_total'].isel(Time=0).plot(ax=axes[0])
ds['Tundra'].isel(Time=0).plot(ax=axes[1])
ds['Shrub'].isel(Time=0).plot(ax=axes[2])

plt.show()

这就是它的样子

在此处输入图像描述

左边的面板是原始数据,对于中间的数据,至少我设法保留了我想要的数据 - 但不是两个巨大的紫色块,我想保留地图,将所选区域之外的所有值设置为零。右边的面板本来打算成为中间面板的“反面”,但我在那里完全失败了。感觉这应该是一件容易的事,但我就是想不通!

标签: where-clausemasknetcdfpython-xarray

解决方案


这似乎主要是逻辑方面的问题,以及用于处理 NaN 的方法。

以下似乎对我有用:

tundra = shrub_total.where((np.isnan(shrub_total)==True)|
                          ((shrub_total.Lat>60)&(shrub_total.Lat<75)), 0)

shrub = shrub_total.where((np.isnan(shrub_total)==True)|
                        ((shrub_total.Lat<60)|(shrub_total.Lat>75)), 0)
  • 我将shrub逻辑更改为 OR 语句(我们想要屏蔽小于 60 或大于 75 - 某处不可能两者兼有!)。
  • 我们使用 np.isnan()==True 而不是 ()!=np.nan。我不确定为什么我们不能像你那样对待这个......这需要进一步改变逻辑。

请注意,我不使用 python,所以这可能非常 hacky,我相信其他人会有一个更优雅和知识渊博的答案,但它引起了我的兴趣,所以我尝试了 :)


推荐阅读