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]]
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]]
c = [[i,j] for i in (a) for j in (b)]
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]])
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], ...])
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