初始化和填充numpy数组的最佳方法? [英] Best way to initialize and fill an numpy array?
问题描述
我想初始化并填充numpy
数组.最好的方法是什么?
I want to initialize and fill a numpy
array. What is the best way?
这符合我的预期:
>>> import numpy as np
>>> np.empty(3)
array([ -1.28822975e-231, -1.73060252e-077, 2.23946712e-314])
但这不是:
>>> np.empty(3).fill(np.nan)
>>>
什么都没有?
>>> type(np.empty(3))
<type 'numpy.ndarray'>
在我看来,np.empty()
调用返回的是正确类型的对象,所以我不明白为什么.fill()
无法正常工作?
It seems to me that the np.empty()
call is returning the correct type of object, so I don't understand why .fill()
is not working?
首先分配np.empty()
的结果可以正常工作:
Assigning the result of np.empty()
first works fine:
>>> a = np.empty(3)
>>> a.fill(np.nan)
>>> a
array([ nan, nan, nan])
为什么要分配给变量才能使用np.fill()
?我想念一个更好的选择吗?
Why do I need to assign to a variable in order to use np.fill()
? Am I missing a better alternative?
推荐答案
np.fill
修改数组,并返回None
.因此,如果您将结果分配给名称,则它将获得None
的值.
np.fill
modifies the array in-place, and returns None
. Therefor, if you're assigning the result to a name, it gets a value of None
.
一种替代方法是使用返回nan
的表达式,例如:
An alternative is to use an expression which returns nan
, e.g.:
a = np.empty(3) * np.nan
这篇关于初始化和填充numpy数组的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!