如果没有找到元素,哪种方法可以有效地输出 np.argmax(array > value) 中的最后一个值而不是 0?

Which is an efficient way to output the last value in np.argmax(array > value) instead of 0 if no element was found?

我们取 np.array:

array = np.array([[1, 4], 
                 [0, 3], 
                 [2, 3]])

我使用此代码查找第一列中的第一个元素,其中值大于阈值:

index = np.argmax(array[:, 0] > threshold)

现在采用阈值 = 1,我得到了预期的索引:

>>index = 2

但是如果我选择一个大于 2 的值,则输出为 0。这会弄乱我的程序,因为我想取最后一个值而不是第一个值,以防没有元素满足阈值。

在这种情况下,是否有一种有效的方法来获取数组的最后一个值?

编辑:

我实际上不明白这对我有什么帮助:

我宁愿寻找像 argmax return False 而不是 0.

这样的东西

@Divakar 和@Achintha Ihalage 的解决方案比较

import numpy as np
import time

def first_nonzero(arr, axis, invalid_val=-1):
    mask = arr != 0
    return np.where(mask.any(axis=axis), mask.argmax(axis=axis), invalid_val)


array = np.random.rand(50000, 50000) * 10
test = array[:, 0]
threshold = 11

t1 = time.time()
index1 = np.argmax(array[:, 0] > threshold) if any(array[:, 0] > threshold) else len(array[:, 0])-1
elapsed1 = time.time() - t1

t2 = time.time()
index2 = first_nonzero(array[:, 0] > threshold, axis=0, invalid_val=len(array[:, 0])-1)
elapsed2 = time.time() - t2

print(index1, "time: ", elapsed1)
print(index2, "time: ", elapsed2)
>>49999 time:  0.012960195541381836
>>49999 time:  0.0009734630584716797

所以@Divakar 的解决方案非常快!非常感谢!

这是一种效率稍低的方法,但您可以利用 numpy.argwhere

#check whether there are elements exceeding the threshold
present = np.argwhere(array[:, 0] > threshold)

if present.size == 0:
  index = len(array)-1
else:
  index = np.argmax(array[:, 0] > threshold)

试试下面的一行。如果至少有一个元素满足条件,您将获得 argmax 索引。否则取最后一个索引。

index = np.argmax(array[:,0]>threshold) if any(array[:,0]>threshold) else  len(array[:,0])-1