我想在 2D numpy 数组上应用蒙版。但它不能正常工作。假设我有
val(lat, lon) ---> my 2D array (20, 30)
Mask_lat = np.ma.masked_array(lat, mask=latmask) ---> masked lat (5,)
Mask_lon = np.ma.masked_array(lon, mask =lonmask) ---> masked lon (8,)
Maks_val = np.ma.masked_array(val, mask=mask_lat_lon) ---> ?
我不知道如何传递正确的 mask_lat_lon
来屏蔽 val (5,8)
。如果有人指导我,我将不胜感激。
提前谢谢你。
最佳答案
如果我正确理解你的问题,你有两个一维数组,它们代表二维数组中的 y 和 x(纬度和经度)位置。您想要根据二维数组中的 x/y 位置来屏蔽区域。
要理解的关键部分是二维数组的掩码也是二维的。
例如,让我们屏蔽二维数组的单个元素:
import numpy as np
z = np.arange(20).reshape(5, 4)
mask = np.zeros(z.shape, dtype=bool)
mask[3, 2] = True
print z
print np.ma.masked_array(z, mask)
这会产生:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 -- 15]
[16 17 18 19]]
在您的例子中,您有两个 1D x 和 y 数组,您需要从中创建 2D 蒙版。例如:
import numpy as np
x = np.linspace(-85, -78, 4)
y = np.linspace(32, 37, 5)
z = np.arange(20).reshape(5, 4)
xmask = (x > -82.6) & (x < -80)
ymask = (y > 33) & (y < 35.6)
print xmask
print ymask
然后我们需要使用广播将它们组合成一个 2D 蒙版:
mask = xmask[np.newaxis, :] & ymask[:, np.newaxis]
使用 newaxis
(或 None
,它们是同一个对象)进行切片会在该位置添加一个新轴,将一维数组转换为二维数组。如果您之前已经看过这个,快速了解一下 xmask[np.newaxis, :]
和 ymask[:, np.newaxis]
的样子会很有用:
In [14]: xmask
Out[14]: array([False, False, True, False], dtype=bool)
In [15]: ymask
Out[15]: array([False, True, True, False, False], dtype=bool)
In [16]: xmask[np.newaxis, :]
Out[16]: array([[False, False, True, False]], dtype=bool)
In [17]: ymask[:, np.newaxis]
Out[17]:
array([[False],
[ True],
[ True],
[False],
[False]], dtype=bool)
mask
将是(请记住 True
元素被屏蔽):
In [18]: xmask[np.newaxis, :] & ymask[:, np.newaxis]
Out[18]:
array([[False, False, False, False],
[False, False, True, False],
[False, False, True, False],
[False, False, False, False],
[False, False, False, False]], dtype=bool)
最后,我们可以根据此掩码从 z
创建一个二维掩码数组:
arr = np.masked_array(z, mask)
这给了我们最终的结果:
[[ 0 1 2 3]
[ 4 5 -- 7]
[ 8 9 -- 11]
[12 13 14 15]
[16 17 18 19]]
关于python - 掩码二维 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34860570/