Let us explore this function in detail in this tutorial.
NumPy Squeeze() Function Syntax
The function has a simple and descriptive syntax as shown in the following snippet:
Function Parameters
The function parameters are described in the list below:
- a – defines the input array
- axis – selects a subset of the length in the specified shape
Function Return Value
The function returns the input array with all the subsets of the dimension of the length removed.
Illustration
The following code shows an illustration of how the squeeze function works.
import numpy as np
arr = np.array([[[10], [20], [30]]])
print(f"input array shape: {arr.shape}")
squeezed = np.squeeze(arr)
print(f"squeezed array shape: {squeezed.shape}")
The code uses the squeeze function to remove the axis with a length of 1. The shape of the array changes from (1,3,1) to (3,) as follows:
squeezed array shape: (3,)
You can also specify the target axis as shown in the following example:
print(f"input array shape: {arr.shape}")
squeezed = np.squeeze(arr, axis=0)
print(f"squeezed array shape: {squeezed.shape}")
The function will apply the squeeze operation on axis 0. The resulting array shape is as follows:
squeezed array shape: (3, 1)
If you specify an axis which length is not equal to 1, the function will return an error as shown in the following:
print(f"input array shape: {arr.shape}")
squeezed = np.squeeze(arr, axis=1)
print(f"squeezed array shape: {squeezed.shape}")
The following image illustrates a value error:
Suppose you apply the squeeze function to an array of shape (1,1). Consider the following example:
print(f"input array shape: {arr.shape}")
squeezed = np.squeeze(arr, axis=1)
print(f"squeezed array shape: {squeezed.shape}")
This returns an array of shape (1,) as shown in the following output:
squeezed array shape: (1,)
Conclusion
Throughout this tutorial, we explored the various parts of the NumPy squeeze function and how to apply it to different array types. Read more related artiles at Linux Hint.