在Numpy数组中查找子列表的索引 [英] Finding the index of a sublist in a Numpy Array
问题描述
我正在努力寻找Numpy数组中子列表的索引.
I am struggling with finding the index of a sublist in a Numpy Array.
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])
,为什么不是呢?另外我该如何实现此输出?
which I cannot explain to me. Shouldn't the output be array([1, 2])
and why is it not? Also how can I achieve this output?
推荐答案
如果我正确理解,这是我的主意:
If I understand correctly, here's my idea:
>>> 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
正在此处的行中广播.)
a boolean array where for each row the True
/False
value indicates if the value in a
is equal to the corresponding value in sub
. (sub
is being broadcasted along the rows here.)
np.all(a == sub,axis = 1)
给您
>>> np.all(a == sub, axis=1)
array([False, True, True])
一个布尔数组,对应于等于 sub
的 a
行.
a boolean array corresponding to the rows of a
that are equal to sub
.
在此子结果上使用 np.where
可以为您提供此布尔数组为 True
的索引.
Using np.where
on this sub-result gives you the indices where this boolean array is True
.
有关您的尝试的详细信息:
np.where(a == sub)
(不需要 tolist
)为您提供了两个数组,它们共同指示数组 a ==处的索引sub
是 True
.
np.where(a == sub)
(the tolist
is unnecessary) gives you two arrays which together indicate the indices where the array a == sub
is 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 == sub
是 True
,即
If you would zip these two arrays together you would get the row/column indices where a == sub
is True
, i.e.
>>> 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)
这篇关于在Numpy数组中查找子列表的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!