Skip to content

Shape Manipulation & Reshape

shape tells the size of each dimension.

shape
import numpy as np
 
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape)  # (2, 3)

Reshape changes the dimension layout without changing the underlying data or copying it — it just reinterprets the same flat block of memory with a new shape.

reshape
import numpy as np
 
arr = np.arange(1, 13)  # 1..12
mat = arr.reshape(3, 4) # 3 rows, 4 cols
print(mat)
sketch Reshaping (3, 4) into (4, 3) p5.js
The same 12 values, read out in the same order, just wrapped into a different grid shape.
reshape-auto
import numpy as np
 
arr = np.arange(12)
mat = arr.reshape(3, -1)
print(mat.shape)  # (3, 4)
ravel
import numpy as np
 
mat = np.array([[1, 2], [3, 4]])
flat = mat.ravel()
print(flat)
flatten
import numpy as np
 
mat = np.array([[1, 2], [3, 4]])
flat = mat.flatten()
print(flat)

Convert a 1D array into a column vector:

newaxis
import numpy as np
 
arr = np.array([1, 2, 3])
col = arr[:, None]
print(col)
print(col.shape)  # (3, 1)
expand
import numpy as np
 
arr = np.array([1, 2, 3])
arr2 = np.expand_dims(arr, axis=0)
print(arr2.shape)  # (1, 3)
squeeze
import numpy as np
 
arr = np.array([[[1], [2], [3]]])
print(arr.shape)           # (1, 3, 1)
print(np.squeeze(arr).shape)  # (3,)

Transposing is a special case of reshaping — it also returns a view, never a copy.

For 2D:

transpose
import numpy as np
 
mat = np.array([[1, 2, 3], [4, 5, 6]])
print(mat.T)
diagram Shape-changing toolbox mermaid
Different tools for growing, shrinking, or rearranging dimensions without touching the underlying data.

Continue to: Broadcasting in NumPy to learn how NumPy applies operations between different shapes.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading