我有一个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
做的排序也很慢。有没有更好的方法来实现这个目标?
如果将操作顺序翻转过来,可以在一行中完成:
把它分解:
后两个步骤可以用intersect1D代替。可能也有点问题。不知道如何避免,除非你能保证你的ind数组是有序的。
相关问题 更多 >
编程相关推荐