NumPy | squeeze method
Start your free 7-days trial now!
Numpy's squeeze(~)
method returns a Numpy array with redundant axes removed. Check the examples below for clarification.
Parameters
1. a
| array-like
The input array.
2. axis
link | int
| optional
The axis you want to remove if redundant. By default, all redundant axises are removed.
Return value
A new Numpy array with redundant axises removed.
Examples
Basic usage
Suppose we have the following 2D array:
a
array([[4], [5], [6]])
Can you see how a
can be expressed simply as an 1D array [4,5,6]
in this case? The squeeze(~)
method allows us to do this:
a.squeeze()
array([4, 5, 6])
The same principle applies for the following case:
a
array([[[1, 2], [3, 4]]])
Here, we have a 3D array, yet it's clear that this can be reduced to a 2D array, like so:
a.squeeze()
array([[1, 2], [3, 4]])
Squeezing only a subset of axis
Suppose we have the following 3D array:
a
array([[[4], [5], [6]]])
It's clear that this can be reduced to either a 2D array or even more compactly to a 1D array. We can specify which dimension to reduce to using the axis
parameter.
Reducing to a 2D array:
np.squeeze(a, axis=0)
array([[4], [5], [6]])
Note that, by default, all redundant axises are removed:
np.squeeze(a)
array([4, 5, 6])