The squeeze()
method removes the dimensions of an array with size 1.
import numpy as np
# create a 3-D array
array1 = np.array([[[0, 1]]])
# squeeze the array
squeezedArray = np.squeeze(array1)
print(squeezedArray)
# Output : [0 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
import numpy as np
array1 = np.array([[[1, 2, 3]]])
# squeeze the array
squeezedArray = np.squeeze(array1)
print(squeezedArray)
Output
[1 2 3]
Example 2: Squeeze an Array With Multiple Single-Dimensional Entries
import numpy as np
array1 = np.array([[1], [2], [3]])
# squeeze the array
squeezedArray = np.squeeze(array1)
print(squeezedArray)
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.
import numpy as np
array1 = np.array([[[1], [2], [3]]])
print('Original Array: \n', array1, "\nShape: ",array1.shape, '\n')
# squeeze array1
array2 = np.squeeze(array1)
print('Squeezed Array: \n', array2, "\nShape: ",array2.shape, '\n')
# squeeze array1 along axis 0
array3 = np.squeeze(array1, axis = 0)
print('Squeezed Array along axis 0: \n', array3, "\nShape: ",array3.shape, '\n')
# squeeze array1 along the last axis
array4 = np.squeeze(array1, axis = -1)
print('Squeezed Array along last axis: \n', array4, "\nShape: ",array4.shape, '\n')
# squeeze array1 along axis 9 and 2
array5 = np.squeeze(array1, axis = (0, 2))
print('Squeezed Array along axis (0, 2): \n', array5, "\nShape: ",array5.shape, '\n')
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.
import numpy as np
array1 = np.array([[[123]]])
# squeeze array1
array2 = np.squeeze(array1)
print('Squeezed Array: \n', array2)
Output
123
Note: Although 123 is a scalar value, it is still considered an array. For example,
print(type(array2)) #<class 'numpy.ndarray'>