python - 在numpy数组中查找最大元素比较的索引

标签 python arrays numpy max

我有一个数组 a,我想找到 a 中给定值仍然大于的最大元素的位置。

在这个例子中:

a = np.array([0, 50, 5, 52, 60])
v = 55

v 大于的最大元素是 52(索引 3)所以我想返回 3。

numpy 函数 argmax() 不适用于此目的,因为它返回第一个元素。使用 numpy 执行此操作的快速且正确的方法是什么?

最佳答案

您可以结合argmaxwhere :

>>> np.nanargmax(np.where(a < v, a, np.nan))
3

np.where替换 v 以上的所有值至 nan在它适用之前nanargmax (在计算中忽略 nan s):

>>> np.where(a < v, a, np.nan)
array([  0.,  50.,   5.,  52.,  nan])

关于python - 在numpy数组中查找最大元素比较的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43707707/

相关文章:

python - collection.abc.* 模块中的抽象类是如何实现的?

python - Ckeditor 在创建后仍然隐藏 - editor.css 为空

javascript - 从 for 循环中推送一个数组并将对象存储到 Mongoose 中,是重复值

javascript - 映射对象返回 "function map() { [native code] } ".. 为什么

python - Numpy - 查找数据点的最大点和值

python - 在正则表达式中用单引号混淆密码

python - 使用 python 和 GObject 自省(introspection)获取 GTK+ 主题颜色

Java:<E 扩展了 Comparable <E>>

python - 将点列表转换为 numpy 二维数组

python - NumPy 数组不是 JSON 可序列化的