使用numpy连接2个列表

时间:2018-03-04 22:16:11

标签: python python-3.x

a = np.array([[0, 1, 2, 3], [4, 5, 6, 7]], dtype=int)
b = np.array([[8], [9]], dtype=int)

结果想要:

  

alist = [[0, 1, 2, 3, 8], [4, 5, 6, 7, 9]] # as np.array

我试过了:

np.concatenate(alist,blist)

np.concatenate((alist,blist))

np.concatenate(alist, blist[0])

for a,b in zip(alist,blist): np.concatenate(a,b)

alist = [*map(np.concatenate, alist, blist)])        

这让我得到了各种错误消息,我试图通过使用下一个试用版来修复。到目前为止没有任何工作。

2 个答案:

答案 0 :(得分:3)

您可以使用np.hstack来实现此目的,这将连接两个数组,但是在第二个轴上。

a = np.array([[0, 1, 2, 3], [4, 5, 6, 7]], dtype=int)
b = np.array([[8], [9]], dtype=int)
>>> np.hstack((a,b))
array([[0, 1, 2, 3, 8],
       [4, 5, 6, 7, 9]])

答案 1 :(得分:3)

您只是错过了axis=1关键字参数。

np.concatenate((a, b), axis=1)

通常np.concatenate适用于0轴(沿阵列向下)。但在这种情况下,您希望沿轴1(跨越数组)连接。有关详细信息,请参阅the glossary