我正在尝试将包含数值和None
值的列表转换为numpy.array
,例如None
替换为numpy.nan
。
例如:
my_list = [3,5,6,None,6,None]
# My desired result:
my_array = numpy.array([3,5,6,np.nan,6,np.nan])
天真的方法失败了:
>>> 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])
解决此问题的最佳方法是什么?