Chr*_* T. -1 python arrays numpy list nonetype
我正在尝试使用以下代码从包含nonetype的列表对象中获取最大值:
import numpy as np
LIST = [1,2,3,4,5,None]
np.nanmax(LIST)
Run Code Online (Sandbox Code Playgroud)
但我收到此错误消息
'>=' not supported between instances of 'int' and 'NoneType'
Run Code Online (Sandbox Code Playgroud)
显然np.nanmax()不适用None.从包含None值的列表对象中获取最大值的替代方法是什么?
在Python 2中
max([i for i in LIST if i is not None])
Run Code Online (Sandbox Code Playgroud)
Python 3 及以上版本很简单
max(filter(None.__ne__, LIST))
Run Code Online (Sandbox Code Playgroud)
或者更详细地说
max(filter(lambda v: v is not None, LIST))
Run Code Online (Sandbox Code Playgroud)
One approach could be -
max([i for i in LIST if i is not None])
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
首先,转换为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])
Run Code Online (Sandbox Code Playgroud)
现在,致电np.nanmax:
print(np.nanmax(x))
5.0
Run Code Online (Sandbox Code Playgroud)
要将max作为整数返回,您可以使用.astype:
print(np.nanmax(x).astype(int)) # or int(np.nanmax(x))
5
Run Code Online (Sandbox Code Playgroud)
这种方法适用于v1.13.1.
| 归档时间: |
|
| 查看次数: |
3366 次 |
| 最近记录: |