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

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

问题描述

我尝试了以下方法:

<预><代码>>>>a = np.array([1,2,3])>>>b = np.array([4,5,6])>>>np.concatenate((a,b),axis=0)数组([1, 2, 3, 4, 5, 6])>>>np.concatenate((a,b),axis=1)数组([1, 2, 3, 4, 5, 6])

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

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

为什么不垂直串联?

解决方案

因为 ab 只有一个轴,因为它们的形状是 (3),axis参数特指要连接的元素的轴.

这个例子应该阐明 concatenate 对轴做了什么.取两个有两个轴的向量,形状为 (2,3):

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

沿第 1 个轴连接(第 1 行,然后是第 2 行):

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

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

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

要获得您呈现的输出,您可以使用 vstack

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

你仍然可以用 concatenate 来做,但你需要先重塑它们:

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

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

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

I tried the following:

>>> 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?

解决方案

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.

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]])

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]])

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]])

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天全站免登陆