将具有 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:47:25  来源:igfitidea点击:

Convert python list with None values to numpy array with nan values

pythonnumpy

提问by Akavall

I am trying to convert a list that contains numeric values and Nonevalues to numpy.array, such that Noneis 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))