The squeeze() method removes the dimensions of an array with size 1.
Here, array1 is a 3-D array with two singleton dimensions (dimensions with size 1). Hence, the two singleton dimensions are removed, and array1 with three dimensions is squeezed to one dimension.
squeeze() Syntax
The syntax of squeeze() is:
numpy.squeeze(array, axis = None)
squeeze() Arguments
The squeeze() method takes two arguments:
array- array to squeezeaxis(optional) - axis along which array is squeezed (None,int,ortuple)
squeeze() Return Value
The squeeze() method returns the squeezed array.
Example 1: Squeeze an Array With a Single-Dimensional Entry
Output
[1 2 3]
Example 2: Squeeze an Array With Multiple Single-Dimensional Entries
Output
[1 2 3]
Example 3: Squeeze Along Specific Axis
If we don't pass an axis argument, it defaults to None, and all dimensions of length are removed.
However, we can specify specific axes to be squeezed.
Output
Original Array: [[[1] [2] [3]]] Shape: (1, 3, 1) Squeezed Array: [1 2 3] Shape: (3,) Squeezed Array along axis 0: [[1] [2] [3]] Shape: (3, 1) Squeezed Array along last axis: [[1 2 3]] Shape: (1, 3) Squeezed Array along axis (0, 2): [1 2 3] Shape: (3,)
Example 4: Squeeze With All Dimensions of Length 1
If all dimensions are of length 1, it returns a scalar value.
Output
123
Note: Although 123 is a scalar value, it is still considered an array. For example,
print(type(array2)) #<class 'numpy.ndarray'>