0

I would like to convert 2 numpy arrays such as these ones:

a = [[1, 2, 3]]
b = [[100, 200, 300]]

to an array like below.

[[1, 100], [1, 200], [1, 300], [2, 100], [2, 200], [3, 300], [3, 100], [3, 200], [3, 300]]   

Is this possible in NumPy?

Thanks in advance.

(edited to clarify the point of this question.) I'm trying to find a numpy way of solution.

4
  • Is this for school? Commented Dec 13, 2018 at 10:59
  • Possible duplicate of Get the cartesian product of a series of lists? Commented Dec 13, 2018 at 11:00
  • 1
    Guys, this is for numpy arrays, not Python lists or dictionaries. Commented Dec 13, 2018 at 11:04
  • a and b are lists, as is the desired result. The itertools. product works fine (though it produces a list of tuples). Commented Dec 13, 2018 at 17:04

1 Answer 1

1

This is a job for meshgrid and stack:

a = np.array([ [1, 2, 3] ])
b = np.array([ [100, 200, 300] ])

print(np.stack(np.meshgrid(a, b)).T.reshape(-1,2))

The first creates a tuple of coordinate on the grid, the second stacks them. Then you just need to transpose and flatten.

Sign up to request clarification or add additional context in comments.

1 Comment

This is what I've been trying to find out. Thanks for your answer.

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.