【问题标题】:Getting index of first occurrence in each row获取每行中第一次出现的索引
【发布时间】:2014-07-15 04:00:54
【问题描述】:

我有这个充满布尔值的数组:

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

       [[False, False, True, False, True, False],
        [ True, False, False, False, False, False]],

       [[ True, False, False, False, False, False],
        [ True, False, False, False, False, False]]], dtype=bool)

我想在每一行的每一列中获取第一次出现 True 的索引,所以答案是这样的:

array([[0,0,0],
      [0,1,0],
      [1,0,2],
      [1,1,0],
      [2,0,0],
      [2,1,0]])

有没有简单快捷的方法?

【问题讨论】:

  • 您想要第一次出现,还是所有出现?您的措辞建议前者,而您的示例输出建议后者。
  • 我想在每一行的每一列中第一次出现 - 一旦我们在一列中找到 True,移动到下一列,寻找 True,切换到下一行,重复。在使用 3d 数组时,我很难找到正确的措辞,抱歉。
  • 根据this answer 获取项目的第一个索引将出现在 numpy 2.0 中。
  • 您的示例输入和输出有问题,您的数组的形状为(3, 2, 6),您的输出形状为(6, 3),但在输出中您使用从0到2的索引,这是一个@ 987654326@。也许您可以通过以下方式更好地描述您的问题:遍历轴 x,然后遍历轴 y 并在轴 z 中找到第一个索引。

标签: python arrays numpy boolean


【解决方案1】:

目前无法测试,但我认为这应该可行

arr.argmax(axis=1).T

argmax 在 numpy 1.9 中的 bools 短路,因此对于这个用例,它应该优先于 where 或 nonzero。


编辑好的,所以上面的解决方案不起作用,但是argmax的方法仍然有用:

In [23]: mult = np.product(arr.shape[:-1])

In [24]: np.column_stack(np.unravel_index(arr.shape[-1]*np.arange(mult) +
   ....:                                  arr.argmax(axis=-1).ravel(),
   ....:                                  arr.shape))
Out[24]:
array([[0, 0, 0],
       [0, 1, 0],
       [1, 0, 2],
       [1, 1, 0],
       [2, 0, 0],
       [2, 1, 0]])

【讨论】:

    【解决方案2】:

    您似乎希望 np.where() 结合 the solution of this answer 来查找唯一行:

    b = np.array(np.where(a)).T
    #array([[0, 0, 0],
    #       [0, 0, 1],
    #       [0, 1, 0],
    #       [1, 0, 2],
    #       [1, 0, 4],
    #       [1, 1, 0],
    #       [2, 0, 0],
    #       [2, 1, 0]], dtype=int64)
    c = b[:,:2]
    d = np.ascontiguousarray(c).view(np.dtype((np.void, c.dtype.itemsize * c.shape[1])))
    _, idx = np.unique(d, return_index=True)
    
    b[idx]
    #array([[0, 0, 0],
    #       [0, 1, 0],
    #       [1, 0, 2],
    #       [1, 1, 0],
    #       [2, 0, 0],
    #       [2, 1, 0]], dtype=int64)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      相关资源
      最近更新 更多