【问题标题】:How to create a mask for nd values in a 2d NumPy array?如何为 2d NumPy 数组中的 nd 值创建掩码?
【发布时间】:2019-09-29 09:48:55
【问题描述】:

如果我想根据二维数组中的一维值创建掩码:

a = np.array([[3, 5], [7, 1]])
threshold = 2
mask = a > threshold
print(a)
print(mask)

我明白了:

[[3 5]
 [7 2]]
[[ True  True]
 [ True False]]

如何为具有 nd 值的二维数组创建这样的掩码?就像以下二维数组中的二维值和二维阈值示例:

b = np.array([[[1, 5], [3, 5]], [[4, 4], [7, 2]]])
threshold = 2, 4
print(b)

看起来像这样:

[[[1 5]
  [3 5]]

 [[4 4]
  [7 2]]]

[1, 5][3, 5][4, 4][7, 2] 是示例性二维值。在threshold 中设置的阈值,第一个值为2,第二个值为4

  • [1, 5] 的单元格应该是 False,因为 1 > 2 == False5 > 4 == True
  • [3, 5] 的单元格应该是 True,因为 3 > 2 == True5 > 4 == True
  • [4, 4] 的单元格应该是 False,因为 4 > 2 == True4 > 4 == False
  • [7, 2] 的单元格应该是False,因为7 > 2 == True2 > 4 == False

我要怎么做才能得到这个对应的面具?

[[ False  True]
 [ False False]]

【问题讨论】:

    标签: arrays numpy mask


    【解决方案1】:

    numpy 广播比较实际上为您很好地处理了这个问题。只需将 threshold 设为 1D 数组并沿最终轴声明 all

    t = np.array([2, 4])
    
    (b > t).all(-1)
    

    array([[False,  True],
           [False, False]])
    

    为了澄清,您的数组实际上是3D。如果你的数组是2D,如下所示,这会有点不同:

    arr = np.array([[1, 5],
                    [3, 5],
                    [4, 4],
                    [7, 2]])
    
    (arr > t).all(-1)
    

    array([False,  True, False, False])
    

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 1970-01-01
      • 2018-09-09
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多