垂直连接两个NumPy数组 [英] Concatenate two NumPy arrays vertically

查看:112
本文介绍了垂直连接两个NumPy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下操作:

>>> a = np.array([1,2,3])
>>> b = np.array([4,5,6])
>>> np.concatenate((a,b), axis=0)
array([1, 2, 3, 4, 5, 6])
>>> np.concatenate((a,b), axis=1)
array([1, 2, 3, 4, 5, 6])

但是,我希望至少有一个结果像这样

However, I'd expect at least that one result looks like this

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

为什么它不是垂直连接的?

Why is it not concatenated vertically?

推荐答案

由于ab都只有一个轴,因为它们的形状为(3),而axis参数专门指代该轴的轴.要连接的元素.

Because both a and b have only one axis, as their shape is (3), and the axis parameter specifically refers to the axis of the elements to concatenate.

此示例应阐明concatenate对轴所做的操作.取两个轴为两个的矢量,其形状为(2,3):

this example should clarify what concatenate is doing with axis. Take two vectors with two axis, with shape (2,3):

a = np.array([[1,5,9], [2,6,10]])
b = np.array([[3,7,11], [4,8,12]])

沿着第一个轴(第一个的行,然后第二个的行)连接:

concatenates along the 1st axis (rows of the 1st, then rows of the 2nd):

np.concatenate((a,b), axis=0)
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

沿第二个轴连接(第一个列,然后第二个列):

concatenates along the 2nd axis (columns of the 1st, then columns of the 2nd):

np.concatenate((a, b), axis=1)
array([[ 1,  5,  9,  3,  7, 11],
       [ 2,  6, 10,  4,  8, 12]])

要获取您显示的输出,可以使用vstack

to obtain the output you presented, you can use vstack

a = np.array([1,2,3])
b = np.array([4,5,6])
np.vstack((a, b))
array([[1, 2, 3],
       [4, 5, 6]])

您仍然可以使用concatenate进行此操作,但是您需要先对其进行重塑:

You can still do it with concatenate, but you need to reshape them first:

np.concatenate((a.reshape(1,3), b.reshape(1,3)))
array([[1, 2, 3],
       [4, 5, 6]])

最后,如评论中所建议,重塑它们的一种方法是使用newaxis:

Finally, as proposed in the comments, one way to reshape them is to use newaxis:

np.concatenate((a[np.newaxis,:], b[np.newaxis,:]))

这篇关于垂直连接两个NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆