在Numpy数组中查找子列表的索引

3

我在寻找Numpy数组中子列表的索引时遇到了困难。

a = [[False,  True,  True,  True],
     [ True,  True,  True,  True],
     [ True,  True,  True,  True]]
sub = [True, True, True, True]
index = np.where(a.tolist() == sub)[0]
print(index)

这段代码给了我:
array([0 0 0 1 1 1 1 2 2 2 2])

我无法解释这个问题。输出应该是array([1, 2]),为什么不是呢?另外我该如何得到这个输出?

你的代码给了我数组 [0 0 0 1 1 1 1 2 2 2 2],而不是 [] - timgeb
1
@timgeb 你是对的。我更新了这个。 - Philipp
实际上,a 的定义也是不正确的,因为它应该是一个形状为 np 数组。 - Philipp
2个回答

8
如果我理解正确,这是我的想法:
>>> a
array([[False,  True,  True,  True],
       [ True,  True,  True,  True],
       [ True,  True,  True,  True]])
>>> sub
>>> array([ True,  True,  True,  True])
>>> 
>>> result, = np.where(np.all(a == sub, axis=1))
>>> result
array([1, 2])

关于这个解决方案的详细信息:

a == sub会给你

>>> a == sub
array([[False,  True,  True,  True],
       [ True,  True,  True,  True],
       [ True,  True,  True,  True]])

一个布尔数组,其中每一行的True/False值表示a中的值是否等于sub中相应的值。(这里sub被沿着行广播。)

np.all(a == sub, axis=1)会给你:

>>> np.all(a == sub, axis=1)
array([False,  True,  True])

一个布尔数组与a的行对应,其中的值等于sub

在这个子结果上使用np.where 将给出该布尔数组为 True 的索引。

关于您的尝试的详细信息:

np.where(a == sub)(不需要使用 tolist)将给出两个数组,它们共同指示数组a == sub中值为 True 的索引。

>>> np.where(a == sub)
(array([0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]),
 array([1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]))

如果将这两个数组合并,您将得到其中 a == subTrue 的行/列索引,即:
>>> for row, col in zip(*np.where(a==sub)):
...:    print('a == sub is True at ({}, {})'.format(row, col))
a == sub is True at (0, 1)
a == sub is True at (0, 2)
a == sub is True at (0, 3)
a == sub is True at (1, 0)
a == sub is True at (1, 1)
a == sub is True at (1, 2)
a == sub is True at (1, 3)
a == sub is True at (2, 0)
a == sub is True at (2, 1)
a == sub is True at (2, 2)
a == sub is True at (2, 3)

1
非常有帮助! - Philipp

0

您也可以使用原生Python而不是使用numpy来完成此操作:

res = [i for i, v in enumerate(a) if all(e==f for e, f in zip(v, sub))]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接