Python

NumPy np.squeeze()

The squeeze function from NumPy removes an axis whose length is equal to one from an input array.

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:

numpy.squeeze(a, axis=None)

Function Parameters
The function parameters are described in the list below:

  1. a – defines the input array
  2. 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
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:

input array shape: (1, 3, 1)
squeezed array shape: (3,)

You can also specify the target axis as shown in the following example:

arr = np.array([[[10], [20], [30]]])
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:

input array shape: (1, 3, 1)
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:

arr = np.array([[[10], [20], [30]]])
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:

arr = np.array([[100]])
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:

input array shape: (1, 1)
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list