Python:NumPy .squeeze()
Numpy’s .squeeze() is used to remove dimensions of size 1 from an array, returning a reshaped array without those singleton dimensions.
Syntax
ndarray.squeeze(axis=None)
Parameters:
axis: Specifies which axis or axes to squeeze. If set toNone(default), all dimensions of size 1 are removed. If any specified axis is not of size 1, it raises aValueError.
Return value:
Returns a view of the input array with the specified singleton dimensions removed.
Example 1: Removing All Singleton Dimensions Using .squeeze()
In this example, .squeeze() is used without the axis parameter to remove all dimensions of size 1 from a 3D array:
import numpy as npnp_array = np.array([[[1, 2, 3], [1, 2, 3]]])print(np_array.shape) # (1, 2, 3)squeezed_array = np.squeeze(np_array)print(squeezed_array.shape)
The output of this code is:
(2, 3)
Example 2: Removing a Specific Dimension Using .squeeze()
In this example, .squeeze(axis=0) removes the first dimension explicitly from an array with shape (1, 2, 3):
import numpy as npnp_array = np.array([[[1, 2, 3], [1, 2, 3]]])squeezed_array = np.squeeze(np_array, axis=0)# Output shape after squeezingprint(squeezed_array.shape)print(squeezed_array)
The output of this code is:
(2, 3)[[1 2 3][1 2 3]]
Only axis 0 is removed since it has size 1, resulting in a 2D array.
Codebyte Example: Removing Multiple Dimensions With a Tuple Using .squeeze()
In this example, .squeeze(axis=(0, 2)) removes both the first and third dimensions from a shape (1, 3, 1):
Axes 0 and 2, both of size 1, will be removed, leaving a flat array of shape (3,).
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours