Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting max value from a list with None elements

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?

like image 625
Chris T. Avatar asked Sep 03 '17 16:09

Chris T.


3 Answers

First, convert to a numpy array. Specify dtype=np.floatX, and all those Nones 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.

like image 188
cs95 Avatar answered Nov 11 '22 16:11

cs95


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 Nones 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)
like image 28
Divakar Avatar answered Nov 11 '22 15:11

Divakar


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))
like image 7
nagendra547 Avatar answered Nov 11 '22 16:11

nagendra547