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
.
One approach could be -
max([i for i in LIST if i is not None])
Sample runs -
In [184]: LIST = [1,2,3,4,5,None]
In [185]: max([i for i in LIST if i is not None])
Out[185]: 5
In [186]: LIST = [1,2,3,4,5,None, 6, 9]
In [187]: max([i for i in LIST if i is not None])
Out[187]: 9
Based on comments from OP
, it seems we could have an input list of all None
s and for that special case, it output should be [None, None, None]
. For the otherwise case, the output would be the scalar max
value. So, to solve for such a scenario, we could do -
a = [i for i in LIST if i is not None]
out = [None]*3 if len(a)==0 else max(a)
In Python 2
max([i for i in LIST if i is not None])
Simple in Python 3 onwards
max(filter(None.__ne__, LIST))
Or more verbosely
max(filter(lambda v: v is not None, LIST))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With