numpy.squeeze() Method | Why do we need numpy.squeeze()?

Learn about the numpy.squeeze() method and why do we need this method?
By Pranit Sharma Last updated : December 22, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Python numpy.squeeze() method

The numpy.squeeze() is used to remove axes of length one from an array. It takes an input array (arr) and an axis parameter. It selects a subset of the entries of length one in the shape. If an axis is selected with a shape entry greater than one, an error is raised.

Syntax of numpy.squeeze() method

Below is the syntax of numpy.squeeze() method:

numpy.squeeze(a, axis=None)

Parameters of numpy.squeeze() method

Here are the list of parameters of numpy.squeeze() method:

  • a: An array-like input data.
  • axis: It is an optional parameter, selects a subset of the entries of length one in the shape.

Return value of numpy.squeeze() method

It returns the same input array as an output but with all or a subset of the dimensions of length 1 removed. This is always arr itself or a view into arr. An important point is that if all axes are squeezed, the result is a 0d array and not a scalar.

Let us understand with the help of an example,

Example of numpy.squeeze() method

Python code to demonstrate that why do we need numpy.squeeze()

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([[[0], [1], [2]]])

# Display original array
print("Original Array:\n",arr,"\n")

# First look at the shape of the array
print("Shape of array:\n",arr.shape,"\n")

# Removing an axes of length one using squeeze
res = np.squeeze(arr, axis=0).shape

# Display result
print("Squeezed array shape:\n",res,"\n")


Example: numpy.squeeze() Method | Why do we need numpy.squeeze()?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.