What is the numpy.squeeze() in NumPy?
NumPy is a very powerful library provided by Python, which helps us to perform complex and high-computational calculations. There are a lot of functions that help us to manipulate arrays and use them according to our needs. One such function is the NumPy squeeze() function.
The NumPy squeeze() function helps us to remove the one-dimensional entry from the original shape of the array. In other ways, the squeeze() function is used to remove an axis of length 1 from the original array.
If the dimensions of an input array are (1, 2, 3), then the squeeze() function will remove the one-dimension entry. Hence the new shape would be (2, 3).
Syntax
The syntax for NumPy squeeze() is:
Parameters
The parameters that NumPy squeeze() takes are:
- arr: This mandatory parameter represents the input array.
- axis: This optional parameter selects a subset of the entries in the shape of an array. The default value for this parameter is None.
Return Type
The return type of this function is an array, with all the subsets of the dimension of unit length removed.
Examples
-
Basic example of NumPy squeeze()
In this example, we will take a three-dimensional array having 1 as one of its dimensions. With the help of the NumPy squeeze() function, we will remove the single-dimension entries from the original shape of the array.
Output
-
Using NumPy squeeze() on an array created using arange() and reshape()
In this example, we will use the NumPy squeeze() function on an array created using arange() and reshape() methods. These methods will help us to generate arrays with continuous values with specified dimensions.
Output
-
Using NumPy squeeze() when ValueError occurs
As discussed earlier, there are two parameters for squeeze(); arr and axis (optional). If an axis is selected with the entry of shape being greater or equal to 1, an error is raised, called ValueError.
Output
Conclusion
- In this article, we learned about the NumPy squeeze() function, a method used to remove the one-dimensional entry from the original shape of the array.
- With the help of some examples, we were able to understand the different use cases of NumPy squeeze() function.
- We looked at a special scenario in which, on increasing the axis value more than or equal to 1, we get a ValueError.