0
0
NumpyHow-ToBeginner ยท 3 min read

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:

  • a is the input array.
  • axis is 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 axis value outside the valid range. The axis must be between -a.ndim-1 and a.ndim.
  • Confusing np.expand_dims with reshape or newaxis. While related, expand_dims is 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

ParameterDescription
aInput array to expand
axisPosition to insert new axis (int, can be negative)
ReturnsArray 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.