Python Numpy:在给定索引数组的最小值的数组中查找元素索引的有效方法

Python Numpy:在给定索引数组的最小值的数组中查找元素索引的有效方法,python,python-3.x,numpy,Python,Python 3.x,Numpy,假设我有一个numpy数组a=np.array([1,5,3,2,4,6,7])。现在我有了另一个numpy数组b=np.array([-1,-2,3,2,-1,-3])。b的长度小于或等于a。我想找到a中最小元素的索引I,这样b[I]>0。因此,在上面的示例中,结果将是3,因为根据b只有索引2、3有效,并且a[2]==3和a[3]==2,所以选择了索引3 我目前的解决办法是 smallest = np.inf index = None for i in range(le

假设我有一个numpy数组
a=np.array([1,5,3,2,4,6,7])
。现在我有了另一个numpy数组
b=np.array([-1,-2,3,2,-1,-3])
b
的长度小于或等于
a
。我想找到
a
中最小元素的索引
I
,这样
b[I]>0
。因此,在上面的示例中,结果将是
3
,因为根据
b
只有索引
2、3
有效,并且
a[2]==3
a[3]==2
,所以选择了索引
3

我目前的解决办法是

    smallest = np.inf
    index = None
    for i in range(len(b)):
        if b[i] > 0:
            if(a[i] < smallest):
                smallest = a[i]
                index = i
minimate=np.inf
索引=无
对于范围内的i(len(b)):
如果b[i]>0:
如果(a[i]<最小值):
最小值=a[i]
指数=i

我不确定我是否可以使用numpy更有效地完成它。任何建议都将不胜感激。谢谢。

这里有一种矢量化方法-

In [72]: idx = np.flatnonzero(b>0)

In [73]: idx[a[:len(b)][idx].argmin()]
Out[73]: 3

您可以使用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
一艘班轮:

idx = np.argwhere(a==a[:len(b)][b>0].min())[0]
可理解代码:

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]

它是代码高效的。为了弄清楚它是否在计算上有效,您应该始终分析它。但是一般来说,python
对于带有动态类型检测的
循环来说并不能用类型化数据打败numpy C代码。那
[:len(b)]
的目的是什么?@palpanzer是因为
a
可能比
b
大,但后来我想,
idx
是由
b
决定的,
idx
的索引不能大于
len(b)
,因此对于这种特定情况并不需要。啊,好吧,我想也许这是一些我不理解的聪明优化。。。