w3resource

NumPy: Remove single-dimensional entries from a specified shape


Remove Single-Dimensional Entries

Write a NumPy program to remove single-dimensional entries from a specified shape.
Specified shape: (3, 1, 4).

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 3x1x4 array of zeros
x = np.zeros((3, 1, 4))

# Squeezing the array x to remove single-dimensional entries, 
# resulting in an array with shape (3, 4), and printing its shape
print(np.squeeze(x).shape) 

Sample Output:

(3, 4)

Explanation:

Explanation:

In the above code -

x = np.zeros((3, 1, 4)): This line creates a 3-dimensional NumPy array named x with shape (3, 1, 4) filled with zeros. The middle dimension has a size of 1, which is redundant.

np.squeeze(x): Remove the redundant dimensions (dimensions with a size of 1) from the ‘x’ array. In this case, the second dimension (axis 1) with a size of 1 will be removed.

np.squeeze(x).shape: Get the shape of the array after the redundant dimensions have been removed. The new shape of the array will be (3, 4) because the middle dimension with a size of 1 is removed.

Finally print() function prints the shape of the squeezed array, which is (3, 4).


For more Practice: Solve these Related Problems:

  • Write a NumPy program to remove all singleton dimensions from an array using np.squeeze.
  • Apply np.squeeze on a (3,1,4) array and verify that the resulting shape is (3,4).
  • Create a function that automatically squeezes any input array and checks if the dimensions are reduced correctly.
  • Demonstrate the difference between np.squeeze and np.reshape by comparing outputs on arrays with single dimensions.

Go to:


PREV : Insert New Axis in 2D Array
NEXT : Concatenate 2D Arrays


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.