给定以下二维数组:

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

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

b = np.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处和之后的值向后移动。

其他回答

在我的例子中,我必须向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],
...

我认为一个更直接的解决方案和更快的启动是做以下工作:

import numpy as np
N = 10
a = np.random.rand(N,N)
b = np.zeros((N,N+1))
b[:,:-1] = a

和时间:

In [23]: N = 10

In [24]: a = np.random.rand(N,N)

In [25]: %timeit b = np.hstack((a,np.zeros((a.shape[0],1))))
10000 loops, best of 3: 19.6 us per loop

In [27]: %timeit b = np.zeros((a.shape[0],a.shape[1]+1)); b[:,:-1] = a
100000 loops, best of 3: 5.62 us per loop

使用hstack的一种方法是:

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

我喜欢这个:

new_column = np.zeros((len(a), 1))
b = np.block([a, new_column])

np。Concatenate也可以

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