给定以下二维数组:

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

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

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

当前回答

在numpy数组中添加一个额外的列:

Numpy np。append方法有三个参数,前两个是2D numpy数组,第三个是一个轴参数,指示沿哪个轴追加:

import numpy as np  
x = np.array([[1,2,3], [4,5,6]]) 
print("Original x:") 
print(x) 

y = np.array([[1], [1]]) 
print("Original y:") 
print(y) 

print("x appended to y on axis of 1:") 
print(np.append(x, y, axis=1)) 

打印:

Original x:
[[1 2 3]
 [4 5 6]]
Original y:
[[1]
 [1]]
y appended to x on axis of 1:
[[1 2 3 1]
 [4 5 6 1]]

其他回答

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

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

我认为:

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

更优雅。

对我来说,下一种方法看起来非常直观和简单。

zeros = np.zeros((2,1)) #2 is a number of rows in your array.   
b = np.hstack((a, zeros))

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

使用hstack的一种方法是:

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