【问题标题】:Numpy masking 3D array using np.where() index使用 np.where() 索引的 Numpy 掩码 3D 数组
【发布时间】:2017-02-01 17:28:39
【问题描述】:

我根据几个条件创建了一个索引

transition = np.where((rain>0) & (snow>0) & (graup>0) & (xlat<53.) & (xlat>49.) & (xlon<-114.) & (xlon>-127.)) #indexes the grids where there are transitions

形状为 (3,259711),如下所示:

array([[  0,   0,   0, ...,  47,  47,  47], #hour
       [847, 847, 848, ..., 950, 950, 951], #lat gridpoint
       [231, 237, 231, ..., 200, 201, 198]]) #lon gridpoint

我还有其他几个变量(例如 temp),其形状为 (48, 1015, 1359),对应于小时、纬度、经度。

鉴于索引是我的有效网格点,我如何屏蔽所有变量,如 temp 以便它保留 (48,1015,1359) 形状,但屏蔽索引之外的值。

【问题讨论】:

  • mask 到底是什么意思?对于什么样的操作?对于某些东西,掩码数组 (np.ma) 子类可能很有用。
  • 感谢您的建议。我已经尝试过使用 numpy.ma.masked_where(idx, temp),但是我的形状 IndexError: Inconsistant shape between the condition and the input (got (3, 259711) and (48, 1015, 1359)) @ hpaulj
  • masked_where 想要隐藏值的布尔掩码,而不是 where 生成的索引元组。产生这个where 元组的条件矩阵是什么?
  • @hpaulj 嗯,嗯,好吧,有没有办法使用索引(使用 np.where),这样那些索引就不会被屏蔽,而其余的被屏蔽?

标签: python numpy


【解决方案1】:
In [90]: arr = np.arange(24).reshape(6,4)
In [91]: keep = (arr % 3)==1
In [92]: keep
Out[92]: 
array([[False,  True, False, False],
       [ True, False, False,  True],
       [False, False,  True, False],
       [False,  True, False, False],
       [ True, False, False,  True],
       [False, False,  True, False]], dtype=bool)
In [93]: np.where(keep)
Out[93]: 
(array([0, 1, 1, 2, 3, 4, 4, 5], dtype=int32),
 array([1, 0, 3, 2, 1, 0, 3, 2], dtype=int32))

keep 掩码的简单应用会给出所需值的一维数组。我还可以使用 where 元组进行索引。

In [94]: arr[keep]
Out[94]: array([ 1,  4,  7, 10, 13, 16, 19, 22])

使用keep,或者说它是布尔逆,我可以创建一个掩码数组:

In [95]: np.ma.masked_array(arr,mask=~keep)
Out[95]: 
masked_array(data =
 [[-- 1 -- --]
 [4 -- -- 7]
 [-- -- 10 --]
 [-- 13 -- --]
 [16 -- -- 19]
 [-- -- 22 --]],
             mask =
 [[ True False  True  True]
 [False  True  True False]
 [ True  True False  True]
 [ True False  True  True]
 [False  True  True False]
 [ True  True False  True]],
       fill_value = 999999)

np.ma.masked_where(~keep, arr) 做同样的事情——只是参数顺序不同。它仍然需要布尔掩码数组。

我可以从 where 元组开始做同样的事情:

In [105]: idx = np.where(keep)
In [106]: mask = np.ones_like(arr, dtype=bool)
In [107]: mask[idx] = False
In [108]: np.ma.masked_array(arr, mask=mask)

np.ma 类中可能有一些东西可以通过一次调用完成此操作,但它必须执行相同类型的构造。

这也有效:

x = np.ma.masked_all_like(arr)
x[idx] = arr[idx]

【讨论】:

    猜你喜欢
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 2019-12-23
    相关资源
    最近更新 更多