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

问题描述 投票:5回答:3

我想找到的最大值的指数一维数组numpy的,是不是无穷大。我试过argmax,但是当在我的数组的无穷价值,它只是返回指数。我想出了这个代码似乎很哈克和不安全。有没有更好的解决办法?

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]
python numpy
3个回答
7
投票

一种方法是,以Inf转换为负Inf和使用argmax() -

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

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
投票

这是我会怎么做。转换所有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))
© www.soinside.com 2019 - 2024. All rights reserved.