0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.squeeze in NumPy: Remove Single-Dimension Entries

Use np.squeeze to remove single-dimensional entries from the shape of a NumPy array. It simplifies arrays by eliminating axes with size 1, making data easier to work with.
๐Ÿ“

Syntax

The basic syntax of np.squeeze is:

  • np.squeeze(a, axis=None)

Where:

  • a is the input array.
  • axis is optional; it specifies which single-dimensional axes to remove. If None, all axes of size 1 are removed.
python
np.squeeze(a, axis=None)
๐Ÿ’ป

Example

This example shows how np.squeeze removes single-dimensional entries from an array's shape.

python
import numpy as np

# Create a 3D array with shape (1, 3, 1)
a = np.array([[[1], [2], [3]]])
print('Original shape:', a.shape)

# Use np.squeeze to remove all single-dimensional axes
b = np.squeeze(a)
print('Squeezed shape:', b.shape)
print('Squeezed array:', b)

# Use np.squeeze with axis=0 to remove only the first axis
c = np.squeeze(a, axis=0)
print('Shape after squeezing axis 0:', c.shape)

# Trying to squeeze an axis that is not size 1 raises an error
try:
    np.squeeze(a, axis=1)
except ValueError as e:
    print('Error:', e)
Output
Original shape: (1, 3, 1) Squeezed shape: (3,) Squeezed array: [1 2 3] Shape after squeezing axis 0: (3, 1) Error: cannot select an axis to squeeze out which has size not equal to one
โš ๏ธ

Common Pitfalls

Common mistakes when using np.squeeze include:

  • Trying to squeeze an axis that is not size 1, which causes a ValueError.
  • Not realizing that np.squeeze removes all size 1 axes by default, which may change the array shape more than expected.
  • Using axis parameter incorrectly or with wrong axis indices.

Always check the array shape before and after squeezing to avoid unexpected results.

python
import numpy as np

arr = np.array([[1, 2, 3]])  # Shape (1, 3)

# Wrong: trying to squeeze axis 1 which is size 3
try:
    np.squeeze(arr, axis=1)
except ValueError as e:
    print('Wrong squeeze:', e)

# Right: squeeze axis 0 which is size 1
correct = np.squeeze(arr, axis=0)
print('Correct squeeze shape:', correct.shape)
Output
Wrong squeeze: cannot select an axis to squeeze out which has size not equal to one Correct squeeze shape: (3,)
๐Ÿ“Š

Quick Reference

np.squeeze Cheat Sheet:

ParameterDescription
aInput array to squeeze
axis=NoneAxes to remove if size 1; removes all if None

Returns: Array with single-dimensional entries removed.

ParameterDescription
aInput array to squeeze
axis=NoneAxes to remove if size 1; removes all if None
โœ…

Key Takeaways

Use np.squeeze to remove axes of size 1 from a NumPy array's shape.
By default, np.squeeze removes all single-dimensional axes unless you specify the axis parameter.
Specifying an axis that is not size 1 causes a ValueError.
Check array shapes before and after squeezing to avoid unexpected shape changes.
np.squeeze helps simplify array dimensions for easier data processing.