Reputation: 23
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.
Upvotes: 1
Views: 600
Reputation: 40678
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])
Upvotes: 1