我想找到一个不是无穷大的1D 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]
Run Code Online (Sandbox Code Playgroud)
一种方法是转换Inf为否定Inf和使用argmax()-
np.where(np.isinf(Y),-np.Inf,Y).argmax()
Run Code Online (Sandbox Code Playgroud)
您可以在屏蔽数组上使用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)
Run Code Online (Sandbox Code Playgroud)
产量
3
Run Code Online (Sandbox Code Playgroud)