Find the index of maximum value in numpy exclude zero values

Viewed 342

I have the following numpy:

e = np.array([0, -1.3, 0, -3.9, 0, -0.9, 0])

I want to find the index of the maximum value in the list, but exclude 0.

The following code example returns first element in the list, because its value is 0.

result = np.argmax(e)
print(result)

But I want not to consider zeros in locating the maximum value:

The expected result should be 5 which is the index of the element with -0.9 value.

I do not want to write code that will run on the list iteratively.

Any ideas?

2 Answers

One possible approach would be:

import numpy as np

e = np.array([0, -1.3, 0, -3.9, 0, -0.9, 0])

result = np.nanargmax(np.where(e != 0, e, np.nan))
print(result)

Output

5

Note that this does not change the input array (in this case e).

One simple solution would be to replace 0 with -np.inf

a[a == 0] = -np.inf
np.argmax(a)
>>> 5
Related