3

I know it is possible to use meshgrid to get all combinations between two arrays using numpy.

But in my case I have an array of two columns and n rows and another array that I would like to get the unique combinations.

For example:

a = [[1,1],
     [2,2],
     [3,3]]

b = [5,6]

# The expected result would be:

final_array = [[1,1,5],
               [1,1,6],
               [2,2,5],
               [2,2,6],
               [3,3,5],
               [3,3,6]]

Which method is the fastest way to get this result using only numpy?

Proposed solution

Ok got the result, but I would like to know if this is a reliable and fast solution for this task, if someone could give me any advice I will appreciate.

a_t = np.tile(a, len(b)).reshape(-1,2)  
b_t = np.tile(b, len(a)).reshape(1,-1) 
final_array = np.hstack((a_t,b_t.T)) 
array([[1, 1, 5],
       [1, 1, 6],
       [2, 2, 5],
       [2, 2, 6],
       [3, 3, 5],
       [3, 3, 6]])
kaihami
  • 815
  • 7
  • 18
  • Perform a [cartesian product](https://stackoverflow.com/questions/11144513/cartesian-product-of-x-and-y-array-points-into-single-array-of-2d-points) on the row indices, then index and column stack. – cs95 Dec 10 '19 at 23:20
  • Can you please elaborate? Almost got the right solution, see the edited question – kaihami Dec 10 '19 at 23:40

1 Answers1

0

Kind of ugly, but here's one way:

xx = np.repeat(a, len(b)).reshape(-1, a.shape[1])
yy = np.tile(b, a.shape[0])[:, None]
np.concatenate((xx, yy), axis=1)
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135