2025, Nov 12 09:00
How to Convert a NumPy 3D Array to a 2D Table with Three Columns and Restore the Original Shape
Learn how to reshape a NumPy 3D array to a 2D table with three columns and back again using transpose and reshape. Preserve axis order and reliably restore data.
Turning a 3D NumPy array into a 2D table and then restoring it back sounds straightforward until axis order gets involved. The key is understanding how transpose and reshape interact so that the round trip preserves the original structure.
Problem overview
There is a 3D array with shape (3, 2, 3). The goal is to produce a 2D array with three columns, and then return to the initial 3D layout.
import numpy as np
src = np.array([[[11, 12, 13], [14, 15, 16]],
[[21, 22, 23], [24, 25, 26]],
[[31, 32, 33], [34, 35, 36]]])
flat3 = src.transpose(1, 2, 0).reshape(-1, 3)
print('2D view with three columns:\n', flat3)
What actually happens
The transformation first permutes axes with transpose(1, 2, 0), then reshapes the result into a 2D matrix with three columns. Axis permutation changes the logical order of elements across dimensions, so restoring the original array means rebuilding the 3D structure and undoing the axis swap.
Solution
One way to obtain the same 2D layout with three columns is to reshape to (3, -1) and then transpose. From there, returning to the original 3D array is a matter of transposing back and reshaping to the original shape.
import numpy as np
src = np.array([[[11, 12, 13], [14, 15, 16]],
[[21, 22, 23], [24, 25, 26]],
[[31, 32, 33], [34, 35, 36]]])
# 3D -> 2D with three columns
as_2d = src.reshape(3, -1).T
print('2D (three columns):\n', as_2d)
# 2D -> original 3D
back_3d = as_2d.T.reshape(src.shape)
print('Restored 3D:')
print(back_3d)
If the 2D array was created using transpose(1, 2, 0).reshape(-1, 3) as shown earlier, it can also be restored by first reshaping to a compatible 3D shape and then transposing axes back:
restored_alt = flat3.reshape(2, 3, 3).transpose(2, 0, 1)
print('Restored 3D (alternative):')
print(restored_alt)
A separate flatten step is not required here because reshape already performs the necessary re-interpretation of the underlying data before applying the new shape.
Why this matters
Reshape on its own does not change axis order, while transpose does. Mixing them without a clear plan leads to re-ordered data that cannot be put back by shape changes alone. Being explicit about the axis permutation and then reversing it is essential to make the round trip reliable.
Takeaways
When converting a 3D array to 2D, decide whether you are only collapsing dimensions or also permuting axes. If axes were permuted, remember the exact order and invert it when reconstructing. Keep in mind that reshape is sufficient without an explicit flatten in this workflow.