如何在 NumPy 中连接两个一维数组? [英] How do I concatenate two one-dimensional arrays in NumPy?

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

问题描述

我有两个数组 A = [a1, ..., an]B = [b1, ..., bn].我想得到等于

I have two arrays A = [a1, ..., an] and B = [b1, ..., bn]. I want to get new matrix C that is equal to

[[a1, b1],
 [a2, b2],
 ...
 [an, bn]]

如何使用 numpy.concatenate 来实现?

推荐答案

这个非常简单但最快的解决方案怎么样?

How about this very simple but fastest solution ?

In [73]: a = np.array([0, 1, 2, 3, 4, 5])
In [74]: b = np.array([1, 2, 3, 4, 5, 6])
In [75]: ab = np.array([a, b])
In [76]: c = ab.T

In [77]: c
Out[77]: 
array([[0, 1],
       [1, 2],
       [2, 3],
       [3, 4],
       [4, 5],
       [5, 6]])

但是,作为 Divakar 指出出,使用np.column_stack 直接给出如下答案:

But, as Divakar pointed out, using np.column_stack gives the answer directly like:

In [85]: np.column_stack([a, b])
Out[85]: 
array([[0, 1],
       [1, 2],
       [2, 3],
       [3, 4],
       [4, 5],
       [5, 6]])

<小时>

效率(降序)

有趣的是,我的简单解决方案结果证明是最快的.(比 np.concatenate 快一点,比 np.column_stack 并且是 np.vstack)

Interestingly, my simple solution turns out to be the fastest. (little faster than np.concatenate, twice as fast as np.column_stack and thrice as fast as np.vstack)

In [86]: %timeit np.array([a, b]).T
100000 loops, best of 3: 4.44 µs per loop

In [87]: %timeit np.concatenate((a[:,None], b[:,None]), axis=1)
100000 loops, best of 3: 5.6 µs per loop

In [88]: %timeit np.column_stack([a, b])
100000 loops, best of 3: 9.5 µs per loop

In [89]: %timeit np.vstack((a, b)).T
100000 loops, best of 3: 14.7 µs per loop

这篇关于如何在 NumPy 中连接两个一维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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