squeeze/expand_dims
squeeze removes size-1 dimensions and expand_dims adds one back.
In this page:
Syntax
np.expand_dims(arr, axis)
np.squeeze(arr)
squeeze/expand_dims
expand_dims inserts a new axis of length 1 at the position you choose, which is often needed for broadcasting. squeeze removes axes of length 1. You can also add axes with np.newaxis.
Note:
arr[:, np.newaxis] turns a 1-D array into a column.
Example: squeeze/expand_dims
import numpy as np
a = np.array([1, 2, 3])
col = np.expand_dims(a, axis=1)
print(col.shape)
print(a[np.newaxis, :].shape)
print(np.squeeze(col).shape)
# Output:
# (3, 1)
# (1, 3)
# (3,)
Related Topics
Common Mistakes
- Squeezing an axis whose length is not 1
- Losing track of which axis was added
- Using squeeze and unexpectedly collapsing a needed dimension
Chapter Summary
- expand_dims adds a length-1 axis
- squeeze removes length-1 axes
- np.newaxis is a shorthand
- Useful for broadcasting
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: