给定以下二维数组:
a = np.array([
[1, 2, 3],
[2, 3, 4],
])
我想在第二轴上加上一列0,得到:
b = np.array([
[1, 2, 3, 0],
[2, 3, 4, 0],
])
给定以下二维数组:
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]]
其他回答
假设M是一个(100,3)ndarray, y是一个(100,)ndarray追加可以这样使用:
M=numpy.append(M,y[:,None],1)
诀窍在于使用
y[:, None]
这将y转换为(100,1)2D数组。
M.shape
现在给
(100, 4)
在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)
使用hstack的一种方法是:
b = np.hstack((a, np.zeros((a.shape[0], 1), dtype=a.dtype)))
使用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]])