获取每行中首次出现的索引
我有一个充满布尔值的数组:
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]])
有没有简单又快速的方法可以做到这一点呢?
3 个回答
0
在其他回答的基础上,如果你想要找到第一个为真的列的索引,并且在某一行没有包含真值时返回 n
,其中 n
是 a
中列的数量:
first_occs = np.argmax(a, axis=1)
all_zeros = ~a.any(axis=1).astype(int)
first_occs_modified = first_occs + all_zeros * a.shape[1]
3
现在不能测试,但我觉得这个方法应该有效。
arr.argmax(axis=1).T
在numpy 1.9中,argmax
在处理布尔值时会短路,所以在这种情况下,使用argmax
比使用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]])
1
看起来你想用 np.where()
结合 这个答案中的解决方案 来找到独特的行:
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)