给定以下二维数组:

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]]

其他回答

在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]]

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.]])

使用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])

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