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).
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics