numpy的垂直连接两个数组 [英] numpy concatenate two arrays vertically

查看:191
本文介绍了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?

推荐答案

由于两个 A B 只一个轴,因为它们的形状是(3),轴参数具体是指元件的轴来连接

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.

这个例子应该澄清什么连击与轴做。举两个向量有两个轴心,以形(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]])

沿着第一轴连接(第1行,然后第2行):

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

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

沿第2轴连接(第1列,那么第二列):

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

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

获得您presented输出,你可以使用

to obtain the output you presented, you can use

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

您仍然可以做到与连击,但它需要更长的时间:

You can still do it with concatenate, but it takes longer:

a=a.reshape(1,3)
b=b.reshape(1,3)
print concatenate((a,b))

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

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