Python:连接numpy数组行的所有组合

时间:2018-07-27 04:45:02

标签: python arrays numpy concatenation

在python中,需要组合两个二维numpy数组,以便得到的行是输入数组中连接在一起的行的组合。我需要最快的解决方案,以便可以在非常大的阵列中使用。

例如:

我知道了

import numpy as np
array1 = np.array([[1,2],[3,4]])
array2 = np.array([[5,6],[7,8]])

我希望代码返回:

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

2 个答案:

答案 0 :(得分:0)

使用numpy的repeattilehstack的解决方案

摘要

result = np.hstack([
    np.repeat(array1, array2.shape[0], axis=0),
    np.tile(array2, (array1.shape[0], 1))
])

分步说明

我们从两个数组array1array2开始:

import numpy as np
array1 = np.array([[1,2],[3,4]])
array2 = np.array([[5,6],[7,8]])

首先,我们使用array1复制repeat的内容:

a = np.repeat(array1, array2.shape[0], axis=0)

a的内容是:

array([[1, 2],
       [1, 2],
       [3, 4],
       [3, 4]])

然后,我们使用array2重复第二个数组tile。特别是,(array1.shape[0],1)在第一个方向上复制array2次,array1.shape[0]次,在另一个方向上仅1次。

b = np.tile(array2, (array1.shape[0],1))

结果是:

array([[5, 6],
       [7, 8],
       [5, 6],
       [7, 8]])

现在,我们可以使用hstack继续堆叠两个结果:

result = np.hstack([a,b])

实现所需的输出:

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

答案 1 :(得分:0)

对于这个小例子,itertools.product实际上更快。我不知道它如何缩放

alist = list(itertools.product(array1.tolist(),array2.tolist()))
np.array(alist).reshape(-1,4)
相关问题