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]]
4

4 Answers 4

2
c = [[i,j] for i in (a) for j in (b)]
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

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]])

1 Comment

Why use order='F'?
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], ...])

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.