I'm trying to get maximal value from a list object that contains nonetype using the following code:
import numpy as np
LIST = [1,2,3,4,5,None]
np.nanmax(LIST)
But I received this error message
'>=' not supported between instances of 'int' and 'NoneType'
Clearly np.nanmax()
doesn't work with None
. What's the alternative way to get max value from list objects that contain None
values?
First, convert to a numpy array. Specify dtype=np.floatX
, and all those None
s will be casted to np.nan
type.
import numpy as np
lst = [1, 2, 3, 4, 5, None]
x = np.array(lst, dtype=np.float64)
print(x)
array([ 1., 2., 3., 4., 5., nan])
Now, call np.nanmax
:
print(np.nanmax(x))
5.0
To return the max as an integer, you can use .astype
:
print(np.nanmax(x).astype(int)) # or int(np.nanmax(x))
5
This approach works as of v1.13.1
.