Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the index of the maximum non-infinity value in a numpy array?

Tags:

python

numpy

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]
like image 779
ablerks Avatar asked Feb 04 '19 13:02

ablerks


3 Answers

One way would be to convert Inf to negative Inf and use argmax() -

np.where(np.isinf(Y),-np.Inf,Y).argmax()
like image 180
Divakar Avatar answered Oct 09 '22 20:10

Divakar


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
like image 6
Dani Mesejo Avatar answered Oct 09 '22 19:10

Dani Mesejo


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))
like image 3
ninesalt Avatar answered Oct 09 '22 19:10

ninesalt