NumPy ndarray.squeeze()
The numpy.ndarray.squeeze()
method removes single-dimensional (size 1) entries from the shape of an array.
It can operate on the entire array or selectively along a specified axis.
Syntax
ndarray.squeeze(axis=None)
Parameters
Parameter | Type | Description |
---|---|---|
axis | None or int or tuple of ints, optional | The axis or axes to squeeze. If specified, only size-1 dimensions along these axes are removed. If None , all size-1 dimensions are removed. |
Return Value
Returns a new array with size-1 dimensions removed. If no changes occur, it returns the original array.
Examples
1. Removing All Size-1 Dimensions
In this example, we create a multi-dimensional array with some size-1 dimensions and remove them using squeeze()
.
import numpy as np
# Creating a 3D array with shape (1, 3, 1)
arr = np.array([[[1], [2], [3]]])
# Removing all size-1 dimensions
squeezed_arr = arr.squeeze()
# Displaying the original and squeezed shapes
print("Original shape:", arr.shape)
print("Squeezed shape:", squeezed_arr.shape)
# Displaying the squeezed array
print("Squeezed array:", squeezed_arr)
Output:
Original shape: (1, 3, 1)
Squeezed shape: (3,)
Squeezed array: [1 2 3]
Since all size-1 dimensions are removed, the shape changes from (1, 3, 1)
to (3,)
.
2. Using the axis
Parameter in ndarray.squeeze()
Here, we remove a size-1 dimension along a specified axis.
import numpy as np
# Creating a 3D array with shape (1, 3, 1)
arr = np.array([[[10], [20], [30]]])
# Removing only the first dimension (axis=0)
squeezed_axis0 = arr.squeeze(axis=0)
# Removing only the last dimension (axis=2)
squeezed_axis2 = arr.squeeze(axis=2)
# Displaying shapes
print("Original shape:", arr.shape)
print("Shape after squeezing axis=0:", squeezed_axis0.shape)
print("Shape after squeezing axis=2:", squeezed_axis2.shape)
# Displaying squeezed arrays
print("Squeezed array (axis=0):", squeezed_axis0)
print("Squeezed array (axis=2):", squeezed_axis2)
Output:
Original shape: (1, 3, 1)
Shape after squeezing axis=0: (3, 1)
Shape after squeezing axis=2: (1, 3)
Squeezed array (axis=0): [[10]
[20]
[30]]
Squeezed array (axis=2): [[10 20 30]]
Using axis=0
removes the first dimension, changing the shape from (1,3,1)
to (3,1)
.
Using axis=2
removes the last dimension, resulting in a shape of (1,3)
.
3. Attempting to Squeeze a Non-Singleton Dimension
If we specify an axis that does not have a size-1 dimension, an error occurs.
import numpy as np
# Creating a 2D array with shape (2, 3)
arr = np.array([[5, 10, 15],
[20, 25, 30]])
try:
# Attempting to squeeze a non-singleton axis (axis=1, which has size 3)
squeezed_arr = arr.squeeze(axis=1)
print("Squeezed array:", squeezed_arr)
except ValueError as e:
print("Error:", e)
Output:
Error: cannot select an axis to squeeze out which has size not equal to one
Since axis 1 has size 3, it cannot be squeezed, resulting in an error.