- I have multiple two dimensional arrays.
- I want to find all combinations consisting of one row from each array.
Example:
Let's say array A has rows a0, a1, a2. Let's say array B has rows b0, b1
The six combinations are:
a0-b0, a0-b1, a1-b0, a1-b1, a2-b0, a2-b1
Dash represents concatenation (np.hstack
)
How to do that fast for arbitrary number of arrays (say, A, B, C, ...) ?
Fast method for 2 arrays: Combination of all rows in two numpy arrays
Code result for combining 3 arrays:
# input arrays:
[[0 1 2]]
[[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
[[17 18 19 20 21 22 23]
[24 25 26 27 28 29 30]
[31 32 33 34 35 36 37]]
# output:
[[ 0 1 2 5 6 7 8 9 17 18 19 20 21 22 23]
[ 0 1 2 5 6 7 8 9 24 25 26 27 28 29 30]
[ 0 1 2 5 6 7 8 9 31 32 33 34 35 36 37]
[ 0 1 2 10 11 12 13 14 17 18 19 20 21 22 23]
[ 0 1 2 10 11 12 13 14 24 25 26 27 28 29 30]
[ 0 1 2 10 11 12 13 14 31 32 33 34 35 36 37]
[ 0 1 2 15 16 17 18 19 17 18 19 20 21 22 23]
[ 0 1 2 15 16 17 18 19 24 25 26 27 28 29 30]
[ 0 1 2 15 16 17 18 19 31 32 33 34 35 36 37]]
Code:
import numpy as np
def form_combinations(xs):
tot_size = np.sum([x.shape[1] for x in xs])
n_rows = [x.shape[0] for x in xs]
out = np.empty(n_rows + [tot_size])
n_cols = [x.shape[1] for x in xs]
cs = np.cumsum([0] + n_cols)
n = np.newaxis
out[:, :, :, cs[0]:cs[1]] = xs[0][:, n, n, :]
out[:, :, :, cs[1]:cs[2]] = xs[1][n, :, n, :]
out[:, :, :, cs[2]:cs[3]] = xs[2][n, n, :, :]
out = out.reshape(-1, tot_size)
return out
def main():
xs = [
np.arange(3)[np.newaxis, :],
np.arange(5, 20).reshape(3, 5),
np.arange(17, 38).reshape(3, 7)
]
print(xs)
out = form_combinations(xs)
print(out)
main()