Last updated

Reshaping Arrays

Definition: Reshaping changes how the elements are arranged (the shape) without changing the data itself. The total number of elements must stay the same.

Example 1 — 1D to 2D

import numpy as np
a = np.arange(12)        # 0..11
print(a)
b = a.reshape(3, 4)      # 3 rows, 4 columns
print(b)

12 elements can become 3x4, 4x3, 2x6, or 6x2 — but not 5x3 (that needs 15).

Example 2 — flatten back to 1D

import numpy as np
b = np.array([[1, 2], [3, 4]])
print(b.flatten())   # [1 2 3 4]

The handy -1 trick

Use -1 to let NumPy work out one dimension for you:

import numpy as np
a = np.arange(12)
print(a.reshape(2, -1))   # NumPy figures out 6 columns

💡 Tip: reshaping is everywhere in machine learning, where models expect data in a specific shape.

Try it Yourself
Output

          
Ad · responsive