【问题标题】:Return the biggest value less than one from a numpy vector从 numpy 向量返回小于 1 的最大值
【发布时间】:2018-05-18 08:20:21
【问题描述】:

我在python中有一个numpy向量,我想找到向量最大值的索引,条件是它小于1。我有以下示例:

temp_res = [0.9, 0.8, 0.7, 0.99, 1.2, 1.5, 0.1, 0.5, 0.1, 0.01, 0.12, 0.56, 0.89, 0.23, 0.56, 0.78]
temp_res = np.asarray(temp_res)
indices = np.where((temp_res == temp_res.max()) & (temp_res < 1))

但是,我尝试的总是返回一个空矩阵,因为这两个条件无法满足。 HU 想要返回 index = 3 作为最终结果,它对应于 0.99 小于 1 的最大值。我该怎么做?

【问题讨论】:

  • ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()
  • @eugenhu 对于数组是的,但仍然令人困惑,不推荐。

标签: python numpy


【解决方案1】:

您需要在过滤数组后执行max() 函数:

temp_res = np.asarray(temp_res)
temp_res[temp_res < 1].max()

Out[60]: 0.99

如果要查找所有索引,这里有一个更通用的方法:

mask = temp_res < 1
indices = np.where(mask)
maximum = temp_res[mask].max()
max_indices = np.where(temp_res == maximum)

例子:

...: temp_res = [0.9, 0.8, 0.7, 1, 0.99, 0.99, 1.2, 1.5, 0.1, 0.5, 0.1, 0.01, 0.12, 0.56, 0.89, 0.23, 0.56, 0.78]
...: temp_res = np.asarray(temp_res)
...: mask = temp_res < 1
...: indices = np.where(mask)
...: maximum = temp_res[mask].max()
...: max_indices = np.where(temp_res == maximum)
...: 

In [72]: max_indices
Out[72]: (array([4, 5]),)

【讨论】:

  • argmax() 将返回过滤后数组的索引,并且只返回第一次出现...
  • @eugenhu 没有。如果第一个0.99之前有>1的条目,结果是错误的。
  • @liliscent 是的,我明白你的意思,刚刚更新。感谢您的评论。
【解决方案2】:

你可以使用:

np.where(temp_res == temp_res[temp_res < 1].max())[0]

例子:

In [49]: temp_res
Out[49]: 
array([0.9 , 0.8 , 0.7 , 0.99, 1.2 , 1.5 , 0.1 , 0.5 , 0.1 , 0.01, 0.12,
       0.56, 0.89, 0.23, 0.56, 0.78])

In [50]: np.where(temp_res == temp_res[temp_res < 1].max())[0]
    ...: 
Out[50]: array([3])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 2018-08-09
    相关资源
    最近更新 更多