Python: max/min builtin functions depend on parameter order

In [19]: 1>float('nan')
Out[19]: False

In [20]: float('nan')>1
Out[20]: False

The float nan is neither bigger nor smaller than the integer 1.
max starts by choosing the first element, and only replaces it when it finds an element which is strictly larger.

In [31]: max(1,float('nan'))
Out[31]: 1

Since nan is not larger than 1, 1 is returned.

In [32]: max(float('nan'),1)
Out[32]: nan

Since 1 is not larger than nan, nan is returned.


PS. Note that np.max treats float('nan') differently:

In [36]: import numpy as np
In [91]: np.max([1,float('nan')])
Out[91]: nan

In [92]: np.max([float('nan'),1])
Out[92]: nan

but if you wish to ignore np.nans, you can use np.nanmax:

In [93]: np.nanmax([1,float('nan')])
Out[93]: 1.0

In [94]: np.nanmax([float('nan'),1])
Out[94]: 1.0

Leave a Comment