将具有 None 值的 python 列表转换为具有 nan 值的 numpy 数组 [英] Convert python list with None values to numpy array with nan values
本文介绍了将具有 None 值的 python 列表转换为具有 nan 值的 numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将包含数值和 None
值的列表转换为 numpy.array
,这样 None
被替换为 <代码>numpy.nan.
例如:
my_list = [3,5,6,None,6,None]# 我想要的结果:my_array = numpy.array([3,5,6,np.nan,6,np.nan])
天真的方法失败:
<预><代码>>>>我的列表[3, 5, 6, 无, 6, 无]>>>np.array(my_list)array([3, 5, 6, None, 6, None], dtype=object) # 非常有限>>>_ * 2回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:* 不支持的操作数类型:'NoneType' 和 'int'>>>my_array # 普通数组可以处理这些操作数组([ 3., 5., 6., nan, 6., nan])>>>my_array * 2数组([6., 10., 12., nan, 12., nan])解决此问题的最佳方法是什么?
解决方案
您只需显式声明数据类型:
<预><代码>>>>my_list = [3, 5, 6, 无, 6, 无]>>>np.array(my_list, dtype=np.float)数组([ 3., 5., 6., nan, 6., nan])I am trying to convert a list that contains numeric values and None
values to numpy.array
, such that None
is replaces with numpy.nan
.
For example:
my_list = [3,5,6,None,6,None]
# My desired result:
my_array = numpy.array([3,5,6,np.nan,6,np.nan])
Naive approach fails:
>>> my_list
[3, 5, 6, None, 6, None]
>>> np.array(my_list)
array([3, 5, 6, None, 6, None], dtype=object) # very limited
>>> _ * 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
>>> my_array # normal array can handle these operations
array([ 3., 5., 6., nan, 6., nan])
>>> my_array * 2
array([ 6., 10., 12., nan, 12., nan])
What is the best way to solve this problem?
解决方案
You simply have to explicitly declare the data type:
>>> my_list = [3, 5, 6, None, 6, None]
>>> np.array(my_list, dtype=np.float)
array([ 3., 5., 6., nan, 6., nan])
这篇关于将具有 None 值的 python 列表转换为具有 nan 值的 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文