Find the maximum value in the numpy list while ignoring infinite values

Viewed 464

I have the following code:

import numpy as np
from numpy import ma

e = np.array([1, 0.2, 0, 0.3, 0, 0.4, 0])
e = ma.log10(e)
result = np.nanargmax(np.where(e != 0, e, np.nan))

I try to find the highest value in the list after logging (Ignoring 0 values). Since there are zeros in the original list, the result obtained after the log operation for the zeros should be ignored as well.

In the example above the expected result should index 5. bu the actual result is index 2.

What needs to change to achieve the desired result?

2 Answers

Use ma.where instead:

import numpy as np
from numpy import ma

e = np.array([1, 0.2, 0, 0.3, 0, 0.4, 0])
e = ma.log10(e)
result = np.nanargmax(ma.where(e != 0, e, np.nan))

print(result)

Output

5

The reason is that the standard np.where is not mask-aware and will replace the mask values by 0, for example:

np.where(e != 0, e, np.nan)

Output (for np.where)

[nan -0.69897 0. -0.52287875 0. -0.39794001 0.]

To simply mask values with 0-s don't overwrite original arguments list:

import numpy as np
from numpy import ma

e = np.array([1, 0.2, 0, 0.3, 0, 0.4, 0])
e2 = ma.log10(e)
result = np.nanargmax(np.where(e > 0, e2, np.nan))

Result is 0 because log10 is monotonically increasing function - it's the highest for the highest positive argument, which is 1 in your case.

Related