我有一个numpy数组,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执行的排序很慢。有更好的方法来实现这个目标吗?

最佳答案

如果翻转操作顺序,可以在一行中进行操作:

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]

10-04 10:59
查看更多