如何在python中连接两个数组?

2024-09-22 20:33:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有3幅图像的标签,还有它们与测试图像的欧几里德距离。我想把相应的距离和他们的标签放在一起。 标签如下

[[array(['morgan freeman'], dtype='<U14')]

 [array(['ahsan khan'], dtype='<U10')]

 [array(['tom cruise'], dtype='<U10')]

我尝试使用a= np.concatenate((p,q),axis=0)进行连接,p是距离,就像[2554,333,453]q是上面提到的标签。但这给了我一个错误

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


Tags: the图像距离index标签arrayathas
1条回答
网友
1楼 · 发布于 2024-09-22 20:33:13

让我们看看,当您要合并两个阵列时,有两种方法:

问:

[[1 2 3]
 [4 5 6]
 [7 8 9]]

p:

['image1' 'image2' 'image3']

1)将一个附加到另一个的右侧,反之亦然

为了将p与q合并,我们需要将p转换为垂直:p.reshape((p.size, 1))

[['image1']
 ['image2']
 ['image3']]

现在: print(np.concatenate((q, p.reshape((p.size, 1))), axis=1))print(np.hstack((q, p.reshape((p.size, 1)))))

[['1' '2' '3' 'image1']
 ['4' '5' '6' 'image2']
 ['7' '8' '9' 'image3']]

2)将一个附加到另一个的底部,反之亦然: 这更容易: 在这里你必须小心。vtsack和concatenate在这里稍有不同。 您可以将这两个数组直接vstack为:print(np.vstack((q, p)))

[['1' '2' '3']
 ['4' '5' '6']
 ['7' '8' '9']
 ['image1' 'image2' 'image3']]

但是为了连接,需要有两个维度相同的数组。 q的维数为2,p的维数为1。因此,基本上,如果将p设为二维数组的一行,则可以进行连接:print(np.concatenate((q, [p])))

[['1' '2' '3']
 ['4' '5' '6']
 ['7' '8' '9']
 ['image1' 'image2' 'image3']]

我希望这有帮助

相关问题 更多 >