[Numpy-discussion] Choosing the lesser value

nathanielpeterson08 at gmail.com nathanielpeterson08 at gmail.com
Mon Sep 7 15:46:35 EDT 2009


Let

a=np.ma.masked_invalid(np.array([-1,np.nan,-2,-3,     np.nan]))
b=np.ma.masked_invalid(np.array([-2,-3,     -1,np.nan,np.nan]))

I'd like to choose the lesser element (component-wise) of a and b.

If the two elements are comparable, I want the lesser element.
If one element is a number and the other is nan, then I want the number.
And if both elements are nan, then I'd like resultant element be nan.

In other words, I'd like the result to equal

np.array([-2,-3,-2,-3,np.nan])

This is what I've tried:

#!/usr/bin/env python
import numpy as np
a=np.ma.masked_invalid(np.array([-1,np.nan,-2,-3,np.nan]))
b=np.ma.masked_invalid(np.array([-2,-3,     -1,np.nan,np.nan]))
very_large_num=10
a=np.ma.filled(a,very_large_num)
print(a)
# [ -1.  10.  -2.  -3.  10.]
b=np.ma.filled(b,very_large_num)
print(b)
# [ -2.  -3.  -1.  10.  10.]
result=np.ma.where(np.ma.less(a,b),a,b)
print(result)
# [ -2.  -3.  -2.  -3.  10.]

And this almost works, except that:

[*] when both elements are nan, I'm getting my fill value (0) instead of nan.
[*] I can guarantee all elements of a and b are either nan or less than some very_large_num, but if there is a solution that works without declaring very_large_num, I'd prefer that.

What is the numpy way to choose lesser values in this situation?



More information about the NumPy-Discussion mailing list