1

I have a 3D NumPy array

x = np.array([[[0, 0, 0, 0],
               [1, 1, 1, 1],
               [2, 2, 2, 2]],

              [[0, 0, 0, 0],
               [1, 1, 1, 1],
               [2, 2, 2, 2]]])

If I want to flatten the 3D array to 1D array by taking row n°0 of x[0], row n°0 of x[1], row n°1 of x[0], row n°1 of x[1], row n°2 of x[0], row n°2 of x[1], and get the following layout:

[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2]

How can I achieve this? Tried to reshape, flatten, none of them worked.

1 Answer 1

1

You can stack then flatten the array:

>>> np.stack(x, axis=1).flatten()
array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2])
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm! Thanks.

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.