如何在Python中垂直连接两个数组? [英] How to vertically concatenate two arrays in Python?
问题描述
我想使用NumPy包在Python中垂直连接两个数组:
a = array([1,2,3,4])
b = array([5,6,7,8])
我想要这样的东西:
c = array([[1,2,3,4],[5,6,7,8]])
如何使用concatenate
函数做到这一点?我检查了这两个函数,但结果是相同的:
c = concatenate((a,b),axis=0)
# or
c = concatenate((a,b),axis=1)
我们在以下两个功能中都有此功能:
c = array([1,2,3,4,5,6,7,8])
问题是a
和b
都是一维数组,因此只有一个轴可以将它们连接在一起.
相反,您可以使用 vstack
(对于垂直为 v ):
>>> np.vstack((a,b))
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
此外,row_stack
是vstack
函数的别名:
>>> np.row_stack((a,b))
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
还值得注意的是,可以一次堆叠相同长度的多个数组.例如,np.vstack((a,b,x,y))
将有四行.
在内部,vstack
的工作方式是确保每个数组至少具有二维(使用atleast_2D
),然后调用concatenate
在第一轴(axis=0
)上联接这些数组. >
I want to concatenate two arrays vertically in Python using the NumPy package:
a = array([1,2,3,4])
b = array([5,6,7,8])
I want something like this:
c = array([[1,2,3,4],[5,6,7,8]])
How we can do that using the concatenate
function? I checked these two functions but the results are the same:
c = concatenate((a,b),axis=0)
# or
c = concatenate((a,b),axis=1)
We have this in both of these functions:
c = array([1,2,3,4,5,6,7,8])
The problem is that both a
and b
are 1D arrays and so there's only one axis to join them on.
Instead, you can use vstack
(v for vertical):
>>> np.vstack((a,b))
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
Also, row_stack
is an alias of the vstack
function:
>>> np.row_stack((a,b))
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
It's also worth noting that multiple arrays of the same length can be stacked at once. For instance, np.vstack((a,b,x,y))
would have four rows.
Under the hood, vstack
works by making sure that each array has at least two dimensions (using atleast_2D
) and then calling concatenate
to join these arrays on the first axis (axis=0
).
这篇关于如何在Python中垂直连接两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!