将具有 None 值的 python 列表转换为具有 nan 值的 numpy 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19456239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert python list with None values to numpy array with nan values
提问by Akavall
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
.
我正在尝试将包含数值和None
值的列表转换为numpy.array
,从而None
替换为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?
解决这个问题的最佳方法是什么?
采纳答案by Jaime
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])
回答by Udo Klein
What about
关于什么
my_array = np.array(map(lambda x: numpy.nan if x==None else x, my_list))