给定以下二维数组:

a = np.array([
    [1, 2, 3],
    [2, 3, 4],
])

我想在第二轴上加上一列0,得到:

b = np.array([
    [1, 2, 3, 0],
    [2, 3, 4, 0],
])

当前回答

使用numpy.append:

>>> a = np.array([[1,2,3],[2,3,4]])
>>> a
array([[1, 2, 3],
       [2, 3, 4]])

>>> z = np.zeros((2,1), dtype=int64)
>>> z
array([[0],
       [0]])

>>> np.append(a, z, axis=1)
array([[1, 2, 3, 0],
       [2, 3, 4, 0]])

其他回答

np。插入也可以。

matA = np.array([[1,2,3], 
                 [2,3,4]])
idx = 3
new_col = np.array([0, 0])
np.insert(matA, idx, new_col, axis=1)

array([[1, 2, 3, 0],
       [2, 3, 4, 0]])

它沿着一个轴插入值,这里是new_col,在给定索引之前,这里是idx。换句话说,新插入的值将占据idx列,并将最初在idx处和之后的值向后移动。

我认为:

np.column_stack((a, zeros(shape(a)[0])))

更优雅。

使用hstack的一种方法是:

b = np.hstack((a, np.zeros((a.shape[0], 1), dtype=a.dtype)))

在我的例子中,我必须向NumPy数组中添加一列1

X = array([ 6.1101, 5.5277, ... ])
X.shape => (97,)
X = np.concatenate((np.ones((m,1), dtype=np.int), X.reshape(m,1)), axis=1)

后 X.shape => (97,2)

array([[ 1. , 6.1101],
       [ 1. , 5.5277],
...

有点晚了,但还没有人发布这个答案,所以为了完整起见:你可以在一个普通的Python数组上使用列表推导式来完成:

source = a.tolist()
result = [row + [0] for row in source]
b = np.array(result)