满足NumPy数组中值和索引条件的元素的索引

21
我有一个NumPy数组 A,我想知道A中元素等于某个值的索引,以及哪些索引满足某些条件:
import numpy as np
A = np.array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])

value = 2
ind = np.array([0, 1, 5, 10])  # Index belongs to ind

这是我所做的:

B = np.where(A==value)[0]  # Gives the indexes in A for which value = 2
print(B)

[1 5 9]

mask = np.in1d(B, ind)  # Gives the index values that belong to the ind array
print(mask)
array([ True, True, False], dtype=bool)

print B[mask]  # Is the solution
[1 5]

这个解决方案可以工作,但我觉得它有些复杂。另外,in1d 会进行一个比较慢的排序。有没有更好的方法来实现这个功能?

5个回答

22

如果你颠倒操作的顺序,可以在一行中完成:

B = ind[A[ind]==value]
print B
[1 5]

拆解一下:

#subselect first
print A[ind]
[1 2 2 3]

#create a mask for the indices
print A[ind]==value
[False  True  True False]

print ind
[ 0  1  5 10]

print ind[A[ind]==value]
[1 5]

14
B = np.where(A==value)[0]  #gives the indexes in A for which value = 2
print np.intersect1d(B, ind)
[1 5]

2

你可以考虑将 np.where 推迟到最后,像这样:

res = (A == value)
mask = np.zeros(A.size)
mask[ind] = 1
print np.where(res * z)[0]

那不需要任何排序。


2
第二和第三步可以用intersect1D代替。可能还需要进行排序。除非您能保证索引数组已排序,否则不知道该如何避免这种情况。

1

这有点不同 - 我没有进行任何时间测试。

>>> 
>>> A = np.array([1,2,3,4,1,2,3,4,1,2,3,4])
>>> ind = np.array([0,1,5,10])
>>> b = np.ix_(A==2)
>>> np.intersect1d(ind, *b)
array([1, 5])
>>> 

尽管看了@Robb的解决方案后,那可能是做这件事的方法。

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