简体   繁体   English

将二维 numpy 数组的逐行组合连接成二维数组

[英]Concatenating row-wise combinations of 2d numpy arrays into a 2d array

Consider two 2d arrays, A and B .考虑两个二维数组AB

import numpy as np

A = np.array([[1, 4],
              [3, 5],
              [1, 2]])

B = np.array([[2, 3],
              [1, 3]])

I want to build an array arrOut that gives all combinations of the rows of A and the rows of B in a 4-column array.我想构建一个数组arrOut ,它给出了一个 4 列数组A行和B行的所有组合。

The desired output is:所需的输出是:

arrOut = [[1, 4, 2, 3],
          [1, 4, 1, 3],
          [3, 5, 2, 3],
          [3, 5, 1, 3],
          [1, 2, 2, 3],
          [1, 2, 1, 3]] 

I'm hoping to see a solution that could be readily expanded to all combinations of the rows of three 2d arrays to form a six column array, or all combinations of the rows of four 2d arrays to form an 8 column array.我希望看到一个解决方案,它可以很容易地扩展到三个二维数组的行的所有组合以形成一个六列数组,或者四个二维数组的行的所有组合以形成一个 8 列数组。

Using numpy broadcasting and extendable to any number of arrays:使用 numpy 广播并可以扩展到任意数量的数组:

r1,c1 = A.shape
r2,c2 = B.shape
arrOut = np.zeros((r1,r2,c1+c2), dtype=A.dtype)
arrOut[:,:,:c1] = A[:,None,:]
arrOut[:,:,c1:] = B
arrOut.reshape(-1,c1+c2)

output:输出:

[[1 4 2 3]
 [1 4 1 3]
 [3 5 2 3]
 [3 5 1 3]
 [1 2 2 3]
 [1 2 1 3]]

For a 3 array case (Here I used (A,B,A)):对于 3 个数组的情况(这里我使用了 (A,B,A)):

r1,c1 = A.shape
r2,c2 = B.shape
r3,c3 = A.shape 
arrOut = np.zeros((r1,r2,r3,c1+c2+c3), dtype=A.dtype)
arrOut[:,:,:,:c1] = A[:,None,None,:]
arrOut[:,:,:,c1:c1+c2] = B[:,None,:]
arrOut[:,:,:,c1+c2:] = A
arrOut.reshape(-1,c1+c2+c3)

output:输出:

[[1 4 2 3 1 4]
 [1 4 2 3 3 5]
 [1 4 2 3 1 2]
 [1 4 1 3 1 4]
 [1 4 1 3 3 5]
 [1 4 1 3 1 2]
 [3 5 2 3 1 4]
 [3 5 2 3 3 5]
 [3 5 2 3 1 2]
 [3 5 1 3 1 4]
 [3 5 1 3 3 5]
 [3 5 1 3 1 2]
 [1 2 2 3 1 4]
 [1 2 2 3 3 5]
 [1 2 2 3 1 2]
 [1 2 1 3 1 4]
 [1 2 1 3 3 5]
 [1 2 1 3 1 2]]

You can even make a for loop for a N array case.您甚至可以为 N 数组情况创建一个 for 循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM