如何在 Python 中垂直连接两个数组? [英] How to vertically concatenate two arrays in Python?

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

问题描述

我想使用 NumPy 包在 Python 中垂直连接两个数组:

a = array([1,2,3,4])b = 数组([5,6,7,8])

我想要这样的东西:

c = array([[1,2,3,4],[5,6,7,8]])

我们如何使用 concatenate 函数来做到这一点?我检查了这两个函数但结果是一样的:

c = concatenate((a,b),axis=0)# 或者c = 连接((a,b),轴 = 1)

我们在这两个函数中都有这个:

c = array([1,2,3,4,5,6,7,8])

解决方案

问题是 ab 都是一维数组,所以只有一个轴可以连接

相反,您可以使用 vstack(v 表示垂直):

<预><代码>>>>np.vstack((a,b))数组([[1, 2, 3, 4],[5, 6, 7, 8]])

另外,row_stackvstack 函数的别名:

<预><代码>>>>np.row_stack((a,b))数组([[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屋!

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