在 2D numpy 数组中添加一个额外的列 python

Adding an extra in column into 2D numpy array python

我有一个二维 numpy 数组,其形状为 (867, 43)。我的目标是添加一个额外的列(np.nan 值)作为该数组的前导列,以便形状变为 (867, 44).

例如:

# sub-section of array
>>> arr[:2, :5]

array([[-0.30368954,  2.8808107 ,  5.8833385 ,  8.6606045 , 11.242557  ],
       [-0.22719575,  3.0030012 ,  6.065371  ,  8.924864  , 11.561942  ]],
  dtype=float32)

会变成:

# same sub-section
>>> f[:2,:5]

array([[        nan, -0.30368954,  2.8808107 ,  5.8833385 ,  8.6606045 ],
       [        nan, -0.22719575,  3.0030012 ,  6.065371  ,  8.924864  ]],
  dtype=float32)

即随着水平尺寸增加一,值已右移。

查看 stack. Edit: clarification; I am making use of the broadcasting 功能以沿第二个维度插入新轴,然后 hstack 将沿零轴附加轴(hstack 的默认值是行或第一维)。

from numpy import array, hstack, nan, newaxis
a = array([[-0.30368954,  2.8808107 ,  5.8833385 ,  8.6606045 , 11.242557  ],
       [-0.22719575,  3.0030012 ,  6.065371  ,  8.924864  , 11.561942  ]],
  dtype=float32)

tmp = ones((a.shape[0])) * nan # create nan array
print(hstack((tmp[:, newaxis], a))) # append along zero axis 

输出:

[[        nan -0.30368954  2.88081074  5.88333845  8.66060448 11.24255657]
 [        nan -0.22719575  3.00300121  6.06537104  8.92486382 11.5619421 ]]

您可以使用 np.hstack():

import numpy as np

my_arr = np.array([[-0.30368954,  2.8808107 ,  5.8833385 ,  8.6606045 , 11.242557  ],
                [-0.22719575,  3.0030012 ,  6.065371  ,  8.924864  , 11.561942  ]])

col = np.empty((my_arr.shape[0],1))
col[:] = np.nan
np.hstack((col, my_arr))

Returns:

[[        nan -0.30368954  2.8808107   5.8833385   8.6606045  11.242557  ]
 [        nan -0.22719575  3.0030012   6.065371    8.924864   11.561942  ]]

使用np.insert()

>>> import numpy as np
>>> arr
array([[-0.30368954,  2.8808107 ,  5.8833385 ,  8.6606045 , 11.242557  ],
       [-0.22719575,  3.0030012 ,  6.065371  ,  8.924864  , 11.561942  ]],

>>> arr = np.insert(arr, 0, np.nan, axis=0)
>>> arr
array([[        nan, -0.30368954,  2.8808107 ,  5.8833385 ,  8.6606045 , 11.242557  ],
       [        nan, -0.22719575,  3.0030012 ,  6.065371  ,  8.924864  , 11.561942  ]],