2

I would like to create a matrix of pairwise arrays from two arrays of different length, a and b:

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

b = np.array([4,5,6,7])

So, c matrix should look like:

[[1,4], [1,5], [1,6], ..., [3,7]]
mpm
  • 3,534
  • 23
  • 33

4 Answers4

2
c = [[i,j] for i in (a) for j in (b)]
  • 5
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – mx0 Nov 08 '17 at 19:46
0

You can use np.meshgrid().

a = np.array((1, 2, 3))
b = np.array((4, 5, 6, 7))
out = np.stack([each.ravel(order='F') for each in np.meshgrid(a, b)])

out now looks like this:

array([[1, 4],
   [1, 5],
   [1, 6],
   [1, 7],
   [2, 4],
   [2, 5],
   [2, 6],
   [2, 7],
   [3, 4],
   [3, 5],
   [3, 6],
   [3, 7]])
bnaecker
  • 6,152
  • 1
  • 20
  • 33
0

You can also use product from itertools library. product(a, b) will return iterator product between a and b. Using vstack to make it an array.

from itertools import product
np.vstack(product(a, b))

Output

array([[1, 4], [1, 5], [1, 6], ...])
titipata
  • 5,321
  • 3
  • 35
  • 59
0

You can create a 2D numpy array with your two arrays and then swap the axes of the combined array with np.swapaxes to acquire shape you want.

X = np.array([a, b])
swapped_array = X.swapaxes(1,0) 
# X.swapaxes(0,1) returns the same result
Jerrold110
  • 191
  • 1
  • 4