I would like to find the index of the largest value in a 1D numpy array that is not infinity. I've tried argmax, but when there is an infinity value in my array it just return that index. The code that I came up with seems quite hacky and unsafe. Is there a better solution?
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]
One way would be to convert Inf
to negative Inf
and use argmax()
-
np.where(np.isinf(Y),-np.Inf,Y).argmax()
You could use argmax on a masked array, with negative 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)
Output
3
This is how I would do it. Convert all inf
to the smallest number in the array then find the max using 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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With