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:
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.
Python-Numpy Code Editor:
Previous: Write a NumPy program to insert a new axis within a 2-D array.Next: Write a NumPy program to concatenate two 2-dimensional arrays.
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