[英]Numpy: Efficient way of finding the index of the element in an array with the smallest value given an index array
Say I have a numpy array a = np.array([1, 5, 3, 2, 4, 6, 7])
.假设我有一个 numpy 数组a = np.array([1, 5, 3, 2, 4, 6, 7])
。 Now I have another numpy array b = np.array([-1, -2, 3, 2, -1, -3])
.现在我有另一个 numpy 数组b = np.array([-1, -2, 3, 2, -1, -3])
。 The length of b
is smaller than or equal to a
. b
的长度小于或等于a
。 I wanna find the index i
of the smallest element in a
such that b[i] > 0
.我想找到索引i
在最小元素的a
,使得b[i] > 0
。 So in the example above, the result will be 3
since according to b
only indices 2, 3
are valid and a[2] == 3
and a[3] == 2
, so index 3
is chosen.所以在上面的例子中,结果将是3
因为根据b
只有索引2, 3
是有效的,并且a[2] == 3
和a[3] == 2
,所以选择索引3
。
My current solution is我目前的解决方案是
smallest = np.inf
index = None
for i in range(len(b)):
if b[i] > 0:
if(a[i] < smallest):
smallest = a[i]
index = i
I am not sure if I can use numpy to do it more efficiently.我不确定我是否可以使用 numpy 来更有效地完成它。 Any advice is appreciated.任何建议表示赞赏。 Thank you.谢谢你。
Here's one vectorized way -这是一种矢量化方式 -
In [72]: idx = np.flatnonzero(b>0)
In [73]: idx[a[:len(b)][idx].argmin()]
Out[73]: 3
You can use the intermediate results of indices from b to get the right index later, heres a way.您可以使用来自 b 的索引的中间结果稍后获得正确的索引,这是一种方法。
import numpy as np
a = np.array([1, 5, 3, 2, 4, 6, 7])
b = np.array([-1, -2, 3, 2, -1, -3])
indices_to_check = np.where(b > 0)[0]
result = indices_to_check[np.argmin(a[indices_to_check])]
#Output:
3
one liner:一个班轮:
idx = np.argwhere(a==a[:len(b)][b>0].min())[0]
Understandable code:可理解的代码:
shortened_a = a[:len(b)]
filtered_a = shortened_a[b>0]
smallest = filtered_a.min()
indices_of_smallest = np.argwhere(a==smallest)
first_idx = indices_of_smallest[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.