0

I want to create a Cartesian product of two numpy so that the first numpy will be the rows and the second will be the columns. For example get these two numpys:

a = np.array([0,0])
b = np.array([0,1,2,3])

The expected result should be 2d numpy like this:

[[0 0 0]
 [0 0 1]
 [0 0 2]
 [0 0 3]]

The following code does not produce the requested result:

a = np.array([0,0])
b = np.array([0,1,2,3])

_new_ = []
for idx in range(len(a)):
    for i in a:
        newArr = np.append(a[idx], b)
        _new_.append(newArr)

print(np.stack(_new_))

What needs to be changed to produce the desired result?

1
  • I don't get the logic. a has 2 elements, but the result has 3 columns. If appending lists, I'd suggest sticking with lists, and don't try to use np.append (that's a nasty function). Commented Nov 14, 2020 at 19:22

1 Answer 1

2

You can use np.tile with np.column_stack

np.column_stack([np.tile(a, (len(b), 1)), b])

array([[0, 0, 0],
       [0, 0, 1],
       [0, 0, 2],
       [0, 0, 3]])

If you have a a as 2D array

a = np.array([[0, 0], [1, 1]])
b = np.array([0,1,2,3])

np.c_[np.tile(a, (len(b), 1)), np.repeat(b, len(a), axis=0)]

array([[0, 0, 0],
       [1, 1, 0],
       [0, 0, 1],
       [1, 1, 1],
       [0, 0, 2],
       [1, 1, 2],
       [0, 0, 3],
       [1, 1, 3]])
Sign up to request clarification or add additional context in comments.

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.