NumPy Tutorial NumPy Statistics NumPy References

NumPy - squeeze() function



The NumPy squeeze() function remove axes of length one from a.

Syntax

numpy.squeeze(a, axis=None)

Parameters

a Required. Specify the input array (array_like).
axis Optional. It can be None or int or tuple of ints. Selects a subset of the entries of length one in the shape. If an axis is selected with shape entry greater than one, an error is raised.

Return Value

Returns the input array, but with all or a subset of the dimensions of length 1 removed.

Example:

In the example below, squeeze() function is used to remove axes of length one from given array.

import numpy as np

Arr = np.array([[[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]]])

#squeezeing the array
Arr1 = np.squeeze(Arr)

#displaying results
print("shape of Arr:", Arr.shape)
print("Arr is:")
print(Arr)

print("\nshape of Arr1:", Arr1.shape)
print("Arr1 is (squeeze with axis=None):")
print(Arr1)

The output of the above code will be:

shape of Arr: (1, 3, 3)
Arr is:
[[[1 2 3]
  [4 5 6]
  [7 8 9]]]

shape of Arr1: (3, 3)
Arr1 is (squeeze with axis=None):
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Example:

An array can not be squeezed on an axis where the shape is greater than one. Consider the example below:

import numpy as np

#creating an array of shape (1, 3, 1)
Arr = np.array([[[1],[2],[3]]])

#An array can not be squeezed at an axis
#where shape is greater than one. For example
#at axis=1, Arr has shape = 3, Hence 
#squeezing it at axis=1 will raise exception

#squeezeing Arr at axis=0
Arr1 = np.squeeze(Arr, axis=0)

#squeezeing Arr at axis=2
Arr2 = np.squeeze(Arr, axis=2)

#displaying results
print("shape of Arr:", Arr.shape)
print("Arr is:")
print(Arr)

print("\nshape of Arr1:", Arr1.shape)
print("Arr1 is (squeeze with axis=0):")
print(Arr1)

print("\nshape of Arr2:", Arr2.shape)
print("Arr2 is (squeeze with axis=2):")
print(Arr1)

The output of the above code will be:

shape of Arr: (1, 3, 1)
Arr is:
[[[1]
  [2]
  [3]]]

shape of Arr1: (3, 1)
Arr1 is (squeeze with axis=0):
[[1]
 [2]
 [3]]

shape of Arr2: (1, 3)
Arr2 is (squeeze with axis=2):
[[1]
 [2]
 [3]]

❮ NumPy - Array Manipulation