Python:numpy.insert NaN值 [英] Python: numpy.insert NaN value
问题描述
我正在尝试将NaN
值插入到numpy数组的特定索引中.我不断收到此错误:
I'm trying to insert NaN
values to specific indices of a numpy array. I keep getting this error:
TypeError:无法根据规则安全"将数组数据从dtype('float64')强制转换为dtype('int64')
TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'
尝试使用以下代码进行操作.
When trying to do so with the following code.
x = np.array(range(1,11))
x = np.insert(x, 5, np.nan, axis=0)
但是,我可以毫无问题地将NaN
值附加到数组的末尾.
However, I can append NaN
values to the end of the array with no problem.
x = np.array(range(1,11))
x = np.append(x, np.nan)
这是为什么?如何在数组中插入NaN值?
Why is this and how can I insert NaN values in my array?
推荐答案
对于x=np.array(range(1,11))
,默认情况下dtype
是int64
,这将阻止您插入浮点数.
With x=np.array(range(1,11))
, the dtype
by default is int64
, which prevents you to insert a float.
最简单的方法是强制dtype
直接浮动:
The easiest is to force the dtype
to float directly:
x = np.array(range(1, 11), dtype=float)
使用np.insert
时,您只能使用初始数组的dtype
(在引擎盖下创建的临时数组使用输入的dtype
).
With np.insert
, you're limited to the dtype
of the initial array (the temporary arrays created below the hood use the dtype
of the input).
但是,使用np.append
时,实际上是使用np.concatenate
,它会创建一个数组,其输入的最大为dtype
:在您的示例中,x
随后被强制转换为float
.
With np.append
, however, you're actually using np.concatenate
, which creates an array with the "largest" dtype
of its inputs: in your example, x
is then cast to float
.
请注意,您可以简单地使用np.arange
函数:
Note that you could simply use the np.arange
function:
x = np.arange(1, 11, dtype=float)
这篇关于Python:numpy.insert NaN值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!