Numpy 数组添加一列

Numpy array adding a column

python 有点新,我需要使用 numpy 来追加一列,我有一个带 [[1 2 3] [4 5 6]] 的 ndarray a 和另一个带 b [1 7] 的 ndarray 所以最终结果应该是 [[1 2 3 1] [4 5 6 7] 。我试过了

array = np.append(a , b, axis=1) 

但我明白了

all the input arrays must have same number of dimensions

(有道理)。我也试图将它插入到 for 循环中,但根据我在 python 中看到的情况,这些库有一种简单的方法来做事,我想知道是否有更有效的方法?

尝试 numpy.hstack 添加轴到 b -

a = np.array([[1,2,3],[4,5,6]])
b = np.array([1,7])

np.hstack([a,b[:,None]])
array([[1, 2, 3, 1],
       [4, 5, 6, 7]])

备注:

  1. b[:,None] 添加一个轴将 b 从 1D (2,) 转换为 2D (2,1) 数组(与 b.reshape(-1,1) 相同)
  2. np.hstack 现在可以水平堆叠 (2,3)(2,1) 以提供 (2,4) 形数组