将两个数组连接成一个新数组

czfnxgou  于 2021-09-08  发布在  Java
关注(0)|答案(2)|浏览(371)

我有两个数组,

A = np.array([[1,2,3],[4,5,6]])
b = np.array([100,101])

我想连接它们,以便 b 在右边添加了一列,因此我们有了一个新数组 A | b 这大概是:
1 2 3 100
4 5 6 101
我正在以这种方式尝试连接:

new = np.concatenate((A, b), axis=1)

但我得到了下一个错误:

ValueError: all the input arrays must have the same number of dimensions, but the array at index 0 has 2 dimension(s), and the array at index 1 has 1 dimension(s)

如何连接这两个数组?

ax6ht2ek

ax6ht2ek1#

你可以用 column_stack :

>>> np.column_stack((A, b))

array([[  1,   2,   3, 100],
       [  4,   5,   6, 101]])

谁负责 b 不是2d。
使 concatenate 工作,我们手工制作 b 形状 (2, 1) :

>>> np.concatenate((A, b[:, np.newaxis]), axis=1)

array([[  1,   2,   3, 100],
       [  4,   5,   6, 101]])
huwehgph

huwehgph2#

您还可以将一个文件转换为一个垂直堆栈,然后将其转换回原来的位置 np.vstack((A.T,b)).T

相关问题