在 Python 中连接二维 numpy 数组
Concatenating 2 dimensional numpy arrays in Python
我想连接这两个数组
a = np.array([[1,2,3],[3,4,5],[6,7,8]])
b = np.array([9,10,11])
这样
a = [[1,2,3,9],[3,4,5,10],[6,7,8,11]]
尝试使用连接
for i in range(len(a)):
a[i] = np.concatenate(a[i],[b[i]])
出现错误:
TypeError: 'list' object cannot be interpreted as an integer
尝试使用追加
for i in range(len(a)):
a[i] = np.append(a[i],b[i])
出现另一个错误:
ValueError: could not broadcast input array from shape (4,) into shape (3,)
(Whosebug 的新手,如果我没有格式化好请见谅)
您可以使用 hstack
和向量广播:
a = np.array([[1,2,3],[3,4,5],[6,7,8]])
b = np.array([9,10,11])
res = np.hstack((a, b[:,None]))
print(res)
输出:
[[ 1 2 3 9]
[ 3 4 5 10]
[ 6 7 8 11]]
请注意,您不能使用 concatenate
,因为数组有 不同的形状。 hstack
水平堆叠 多维 数组,因此它只是在此处的末尾添加一个新行。需要广播操作(b[:,None]
),以便附加的矢量是垂直的。
你可以这样做:
np.append(a,b.reshape(-1,1),axis=1)
我想连接这两个数组
a = np.array([[1,2,3],[3,4,5],[6,7,8]])
b = np.array([9,10,11])
这样
a = [[1,2,3,9],[3,4,5,10],[6,7,8,11]]
尝试使用连接
for i in range(len(a)):
a[i] = np.concatenate(a[i],[b[i]])
出现错误:
TypeError: 'list' object cannot be interpreted as an integer
尝试使用追加
for i in range(len(a)):
a[i] = np.append(a[i],b[i])
出现另一个错误:
ValueError: could not broadcast input array from shape (4,) into shape (3,)
(Whosebug 的新手,如果我没有格式化好请见谅)
您可以使用 hstack
和向量广播:
a = np.array([[1,2,3],[3,4,5],[6,7,8]])
b = np.array([9,10,11])
res = np.hstack((a, b[:,None]))
print(res)
输出:
[[ 1 2 3 9]
[ 3 4 5 10]
[ 6 7 8 11]]
请注意,您不能使用 concatenate
,因为数组有 不同的形状。 hstack
水平堆叠 多维 数组,因此它只是在此处的末尾添加一个新行。需要广播操作(b[:,None]
),以便附加的矢量是垂直的。
你可以这样做:
np.append(a,b.reshape(-1,1),axis=1)