如何在 Python 中垂直连接两个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29654628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to vertically concatenate two arrays in Python?
提问by Eghbal
I want to concatenate two arrays vertically in Python using the NumPy package:
我想使用 NumPy 包在 Python 中垂直连接两个数组:
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:
我们如何使用该concatenate
函数来做到这一点?我检查了这两个函数,但结果是一样的:
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])
采纳答案by Alex Riley
The problem is that both a
and b
are 1D arrays and so there's only one axis to join them on.
问题是a
和b
都是一维数组,因此只有一个轴可以连接它们。
Instead, you can use vstack
(vfor vertical):
相反,您可以使用vstack
(v表示垂直):
>>> np.vstack((a,b))
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
Also, row_stack
is an alias of the vstack
function:
此外,row_stack
是vstack
函数的别名:
>>> 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.
还值得注意的是,可以一次堆叠多个相同长度的数组。例如,np.vstack((a,b,x,y))
将有四行。
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
).
在幕后,vstack
通过确保每个数组至少有两个维度(使用atleast_2D
)然后调用concatenate
以在第一个轴 ( axis=0
)上连接这些数组来工作。
回答by Ying Xiong
To use concatenate
, you need to make a
and b
2D arrays instead of 1D, as in
要使用concatenate
,您需要a
和b
二维数组,而不是一维,如
c = concatenate((atleast_2d(a), atleast_2d(b)))
Alternatively, you can simply do
或者,你可以简单地做
c = array((a,b))
回答by EdChum
Use np.vstack
:
使用np.vstack
:
In [4]:
import numpy as np
a = np.array([1,2,3,4])
b = np.array([5,6,7,8])
c = np.vstack((a,b))
c
Out[4]:
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
In [5]:
d = np.array ([[1,2,3,4],[5,6,7,8]])
d
?
Out[5]:
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
In [6]:
np.equal(c,d)
Out[6]:
array([[ True, True, True, True],
[ True, True, True, True]], dtype=bool)
回答by EdChum
Maybe it's not a good solution, but it's simple way to makes your code works, just add reshape:
也许这不是一个好的解决方案,但它是使您的代码正常工作的简单方法,只需添加 reshape:
a = array([1,2,3,4])
b = array([5,6,7,8])
c = concatenate((a,b),axis=0).reshape((2,4))
print c
out:
出去:
[[1 2 3 4]
[5 6 7 8]]
In general if you have more than 2 arrays with the same length:
通常,如果您有 2 个以上相同长度的数组:
reshape((number_of_arrays, length_of_array))