gpt4 book ai didi

python - 从 numpy 向量中返回小于 1 的最大值

转载 作者:太空狗 更新时间:2023-10-30 02:37:20 28 4
gpt4 key购买 nike

我在 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 作为最终结果,它对应于小于 1 的最大值 0.99。我该怎么做?

最佳答案

您需要在过滤数组后执行 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]),)

关于python - 从 numpy 向量中返回小于 1 的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50406852/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com