我想在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)
。如果有人指导我,我将不胜感激。
先感谢您。
如果我正确理解了您的问题,则您有两个1D数组,分别代表2D数组中的y和x(经纬度)。您要基于2D数组中x / y位置遮罩区域。
要理解的关键部分是2D阵列的蒙版也是2D。
例如,让我们掩盖2D数组的单个元素:
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
,它们是同一个对象)会在该位置添加一个新轴,从而将1D数组变成2D数组。您之前已经看过此内容,快速浏览一下内容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
基于此蒙版创建2D蒙版数组:
arr = np.masked_array(z, mask)
这给了我们最终结果:
[[ 0 1 2 3]
[ 4 5 -- 7]
[ 8 9 -- 11]
[12 13 14 15]
[16 17 18 19]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句