2016-06-28 128 views
0

我试图在numpy ndarray中插入numpy浮点数。 代码和输出是:在numpy数组中插入numpy.float64元素

和相应的输出是:

type(dos) 
<class 'numpy.ndarray'> 
dos.shape 
(301, 18) 
dos[15] Before 
[ -9.75080030e-02 -8.37110240e-02 -3.13760517e-03 -2.70089494e-03 
    -2.07915835e-03 -1.77532740e-03 -2.03548911e-03 -1.73346437e-03 
    -1.98000973e-04 -1.64015415e-04 -1.99115166e-04 -1.65569761e-04 
    -9.07381374e-05 -7.37546825e-05 -1.48250176e-04 -1.22108731e-04 
    -1.18854648e-04 -9.70416840e-05] 
type(atom[1,0,0]) 
<class 'numpy.float64'> 
atom[1,0,0] 
-4.11 
dos[15] After 
0.0 
type(dos2) 
<class 'numpy.ndarray'> 

其中预期的结果是:

[ -4.11 -9.75080030e-02 -8.37110240e-02 -3.13760517e-03 -2.70089494e-03 
     -2.07915835e-03 -1.77532740e-03 -2.03548911e-03 -1.73346437e-03 
     -1.98000973e-04 -1.64015415e-04 -1.99115166e-04 -1.65569761e-04 
     -9.07381374e-05 -7.37546825e-05 -1.48250176e-04 -1.22108731e-04 
     -1.18854648e-04 -9.70416840e-05] 

从numpy的documentation,我不能看到我错了。 请帮忙。

回答

2

从mentionned该文档:

ARR的副本插入值。请注意,插入不会在原地发生:返回一个新的数组。如果axis是None,out是一个扁平数组。

这意味着你的循环:

是否300无用操作,然后插入一个单一的值,和dos2包含dos301*18值加上一个值(平坦化):

>>> dos = np.random.random((3, 3)) 
>>> dos2 = np.insert(dos, 0, 12) 
>>> dos2 
array([ 12.  , 0.30211688, 0.39685661, 0.89568364, 
     0.14398144, 0.39122099, 0.8017827 , 0.35158563, 
     0.18771122, 0.89938571]) 
>>> dos2[5] 
0.39122099250162556 

你可能想要的是发生那个值元素 in do S:

>>> dos2 = np.empty((dos.shape[0], dos.shape[1] + 1), dtype=dos.dtype) 
>>> for i in range(dos.shape[0]): 
...  dos2[i] = np.insert(dos[i], 0, 12) 
... 
>>> dos2 
array([[ 12.  , 0.30211688, 0.39685661, 0.89568364], 
     [ 12.  , 0.14398144, 0.39122099, 0.8017827 ], 
     [ 12.  , 0.35158563, 0.18771122, 0.89938571]]) 

也可简单地表示为:

>>> dos2 = np.empty((dos.shape[0], dos.shape[1] + 1), dtype=dos.dtype) 
>>> dos2[:, 0] = 12 
>>> dos2[:, 1:] = dos 
1

从你的“预期的结果”看起来你只是想在原本平坦数组开头插入单个值。绝对不需要使用for循环来执行此操作。

>>> insert_value = 100 
>>> orig_array = np.array([1, 2, 3, 4, 5]) 
>>> final_array = np.insert(orig_array, 0, insert_value) 
>>> print(final_array) 
[100 1 2 3 4 5]