从包含 None 元素的列表中获取最大值



我正在尝试使用以下代码从不包含 nonetype 的列表对象中获取最大值:

import numpy as np
LIST = [1,2,3,4,5,None]
np.nanmax(LIST)

但是我收到了此错误消息

'>=' not supported between instances of 'int' and 'NoneType'

显然np.nanmax()不适用于None.从包含None值的列表对象中获取最大值的替代方法是什么?

首先,转换为 numpy 数组。指定dtype=np.floatX,所有这些None都将转换为np.nan类型。

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])

现在,致电np.nanmax

print(np.nanmax(x))
5.0

要将 max 作为整数返回,可以使用.astype

print(np.nanmax(x).astype(int)) # or int(np.nanmax(x))
5

此方法自v1.13.1起有效。

一种方法可能是 -

max([i for i in LIST if i is not None])

示例运行 -

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

基于comments from OP,似乎我们可以有一个所有None的输入列表,对于这种特殊情况,它的输出应该是[None, None, None]的。对于其他情况,输出将是标量max值。所以,为了解决这种情况,我们可以做——

a = [i for i in LIST if i is not None]
out = [None]*3 if len(a)==0 else max(a)

在 Python 2 中

max([i for i in LIST if i is not None])

在 Python 3 以后的版本中很简单

max(filter(None.__ne__, LIST))

或者更详细

max(filter(lambda v: v is not None, LIST))

这是我要做的:

>>> max(el for el in LIST if el is not None)
5

它表面上与其他答案相似,但微妙的不同之处在于它使用生成器表达式而不是列表理解。不同之处在于它不会创建中间列表来存储筛选结果。

您可以使用简单的列表理解来首先过滤掉 Nones:

np.nanmax([x for x in LIST if x is not None])

如果你想更具体地只取数字的max,你可以使用filter和数字抽象基类:

>>> import numbers
>>> filter(lambda e: isinstance(e, numbers.Number), [1,'1',2,None])
[1, 2]

或者,这个的生成器版本:

>>> max(e for e in [1,'1',2,None] if isinstance(e, numbers.Number))
2

由于这是 Python 3,您的错误是 Python 3 下更严格的比较规则:

Python 3.6.1 (default, Mar 23 2017, 16:49:06) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1<None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'NoneType'

Python 2 允许不同对象比较的地方:

Python 2.7.13 (default, Jan 15 2017, 08:44:24) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1<None
False
>>> 1>None
True

因此,当您创建一个numpy数组时,您将获得一个Python对象数组:

>>> np.array([1,2,3,4,5,None])
array([1, 2, 3, 4, 5, None], dtype=object)

所以numpy正在使用底层的Python 3比较规则来比较一个Python对象数组,这是你的错误:

>>> np.max(np.array([1,2,3,4,5,None]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line 2252, in amax
out=out, **kwargs)
File "/usr/local/lib/python3.6/site-packages/numpy/core/_methods.py", line 26, in _amax
return umr_maximum(a, axis, None, out, keepdims)
TypeError: '>=' not supported between instances of 'int' and 'NoneType'

因此,在创建 numpy 数组时,您需要过滤掉None

>>> np.max(np.array([e for e in [1,2,3,4,5,None] if e is not None]))
5

或者将其转换为支持nan的 numpy 类型(并且np.int没有nan):

>>> np.array([1,2,3,4,5,None], dtype=np.float)
array([  1.,   2.,   3.,   4.,   5.,  nan])

但在这种情况下,最大值nan

>>> np.max(np.array([1,2,3,4,5,None], dtype=np.float))
nan

所以使用np.nanmax

>>> np.nanmax(np.array([1,2,3,4,5,None], dtype=np.float))
5.0

使用过滤器来摆脱LIST的所有None
我们正在利用这样一个事实,即过滤器方法需要两个参数。第一个是函数,第二个是可迭代函数。
此函数必须返回可迭代的元素(作为第二个参数提供),该元素将从可迭代对象中删除。我们将 None 作为第一个参数传递,因此所有可迭代对象(LIST)的假对象(在本例中为None)都会被过滤掉。

import numpy as np
LIST = [1,2,3,4,5,None]
filtered_list = list(filter(None, LIST))
np.nanmax(filtered_list) 

编辑:这不会从列表中删除 0

filtered_list = list(filter(None.__ne__, LIST))

Pandas DataFrame有自己的函数,

list.idxmax()通过忽略 NaN 值返回最大值的索引。 查看此 URl 了解更多信息。

最新更新