如何在python中明智地组合两个numpy数组元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17619415/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:41:34  来源:igfitidea点击:

How do I combine two numpy arrays element wise in python?

pythonarrayspython-2.7numpy

提问by James Mertz

I have two numpy arrays:

我有两个 numpy 数组:

A = np.array([1, 3, 5, 7])
B = np.array([2, 4, 6, 8])

and I want to get the following from combining the two:

我想通过将两者结合起来得到以下内容:

C = [1, 2, 3, 4, 5, 6, 7, 8]

I'm able to get something close by using zip, but not quite what I'm looking for:

我可以通过使用来接近一些东西zip,但不是我正在寻找的东西:

>>> zip(A, B)
[(1, 2), (3, 4), (5, 6), (7, 8)]

How do I combine the two numpy arrays element wise?

如何明智地组合两个 numpy 数组元素?



I did a quick test of 50,000 elements in each array (100,000 combined elements). Here are the results:

我对每个数组中的 50,000 个元素(100,000 个组合元素)进行了快速测试。结果如下:

User Ma3x:      Time of execution: 0.0343832323429      Valid Array?:  True
User mishik:    Time of execution: 0.0439064509613      Valid Array?:  True
User Jaime:     Time of execution: 0.02767023558        Valid Array?:  True

Tested using Python 2.7, Windows 7 Enterprise 64-bit, Intel Core i7 2720QM @2.2 Ghz Sandy Bridge, 8 GB Mem

使用 Python 2.7、Windows 7 Enterprise 64 位、Intel Core i7 2720QM @2.2 Ghz Sandy Bridge、8 GB 内存进行测试

采纳答案by Jaime

Use np.insert:

使用np.insert

>>> A = np.array([1, 3, 5, 7])
>>> B = np.array([2, 4, 6, 8])
>>> np.insert(B, np.arange(len(A)), A)
array([1, 2, 3, 4, 5, 6, 7, 8])

回答by mishik

You can try this:

你可以试试这个:

C = sorted(A.tolist() + B.tolist())
  1. A.tolist()will yield [1, 3, 5, 7]
  2. B.tolist()will yield [2, 4, 6, 8]
  3. A.tolist() + B.tolist()- [1, 3, 5, 7, 2, 4, 6, 8]
  4. sorted(...)- [1, 2, 3, 4, 5, 6, 7, 8]
  1. A.tolist()会屈服 [1, 3, 5, 7]
  2. B.tolist()会屈服 [2, 4, 6, 8]
  3. A.tolist() + B.tolist()—— [1, 3, 5, 7, 2, 4, 6, 8]
  4. sorted(...)—— [1, 2, 3, 4, 5, 6, 7, 8]

Without sorting:

不排序:

C = [y for x in zip(A, B) for y in x]

回答by Ma3x

Some answers suggested sorting, but since you want to combine them element-wise sorting won't achieve the same result.

一些答案建议排序,但由于您想将它们组合起来,按元素排序不会达到相同的结果。

Here is one way to do it

这是一种方法

C = []
for elem in zip(A, B):
    C.extend(elem)

回答by J. Martinot-Lagarde

You can also use slices :

您还可以使用切片:

C = np.empty((A.shape[0]*2), dtype=A.dtype)
C[0::2] = A
C[1::2] = B

回答by gashero

>>> import numpy as np
>>> A=np.array([1,3,5,7])
>>> B=np.array([2,4,6,8])
>>> C=np.dstack([A,B])
>>> D=C.reshape((1,8))[0]
>>> D
array([1, 2, 3, 4, 5, 6, 7, 8])