如何在numpy数组中找到最大非无穷大的索引?

时间:2019-02-04 13:05:52

标签: python numpy

我想在不是无限的一维numpy数组中找到最大值的索引。我已经尝试过argmax,但是当我的数组中有一个无穷大值时,它只会返回该索引。我想出的代码似乎很hacky,也不安全。有更好的解决方案吗?

import numpy as np
Y=np.array([2.3,3.5,np.inf,4.4,np.inf,2.5])

idx=np.where(Y==np.max(Y[np.isfinite(Y)]))[0][0]

3 个答案:

答案 0 :(得分:7)

一种方法是将Inf转换为负数Inf并使用argmax()-

np.where(np.isinf(Y),-np.Inf,Y).argmax()

答案 1 :(得分:6)

您可以在掩码数组上使用argmax,且np.inf为负:

import numpy as np

Y = np.array([2.3, 3.5, np.inf, 4.4, np.inf, 2.5], dtype=np.float32)
masked_Y = np.ma.array(Y, mask=~np.isfinite(Y))

idx = np.ma.argmax(masked_Y, fill_value=-np.inf)
print(idx)

输出

3

答案 2 :(得分:2)

这就是我要做的。将所有inf转换为数组中的最小数字,然后使用argmax找到最大值:

Y = np.array([2.3, 3.5, np.inf, 4.4, np.inf, 2.5])
Y[Y == np.inf] = np.min(Y)
print(np.argmax(Y))
相关问题