How to Use np.expand_dims in NumPy: Syntax and Examples
Use
np.expand_dims to add a new axis to a NumPy array at a specified position, increasing its dimensions by one. This is useful to reshape arrays for broadcasting or aligning shapes without changing data.Syntax
The syntax of np.expand_dims is:
np.expand_dims(a, axis)
Where:
ais the input array.axisis the position where the new axis is inserted. It can be a positive or negative integer.
python
np.expand_dims(a, axis)
Example
This example shows how to add a new axis to a 1D array to make it 2D by inserting the axis at position 0 and 1.
python
import numpy as np arr = np.array([1, 2, 3]) # Add new axis at position 0 (makes shape (1, 3)) expanded_0 = np.expand_dims(arr, axis=0) # Add new axis at position 1 (makes shape (3, 1)) expanded_1 = np.expand_dims(arr, axis=1) print('Original shape:', arr.shape) print('Expanded shape axis=0:', expanded_0.shape) print('Expanded array axis=0:\n', expanded_0) print('Expanded shape axis=1:', expanded_1.shape) print('Expanded array axis=1:\n', expanded_1)
Output
Original shape: (3,)
Expanded shape axis=0: (1, 3)
Expanded array axis=0:
[[1 2 3]]
Expanded shape axis=1: (3, 1)
Expanded array axis=1:
[[1]
[2]
[3]]
Common Pitfalls
Common mistakes when using np.expand_dims include:
- Using an
axisvalue outside the valid range. The axis must be between-a.ndim-1anda.ndim. - Confusing
np.expand_dimswithreshapeornewaxis. While related,expand_dimsis clearer for adding a single axis.
python
import numpy as np arr = np.array([1, 2, 3]) # Wrong: axis out of range # np.expand_dims(arr, axis=3) # This will raise an error # Correct: axis within range expanded = np.expand_dims(arr, axis=2) print('Expanded shape:', expanded.shape)
Output
Expanded shape: (3, 1)
Quick Reference
| Parameter | Description |
|---|---|
| a | Input array to expand |
| axis | Position to insert new axis (int, can be negative) |
| Returns | Array with one more dimension |
Key Takeaways
Use np.expand_dims to add a new axis to an array without changing data.
The axis parameter controls where the new dimension is inserted.
Axis must be within the range [-a.ndim-1, a.ndim].
It is useful for preparing arrays for broadcasting or model inputs.
np.expand_dims is clearer and safer than manual reshaping for adding axes.