NumPy: Remove the first dimension from a given array of shape (1,3,4)
Remove first dimension of a (1,3,4) array.
Write a NumPy program to remove the first dimension from a given array of shape (1,3,4).
Sample array:
[[[1, 2, 3, 4],
[0, 1, 3, 4],
[5, 0, 3, 2]]])
Sample Solution:
Python Code:
# Importing NumPy library
import numpy as np
# Creating a NumPy array with a shape of (1, 3, 4) containing nested lists
nums = np.array([[[1, 2, 3, 4],
[0, 1, 3, 4],
[5, 0, 3, 2]]])
# Printing the shape of the array
print('Shape of the said array:')
print(nums.shape)
# Removing the first dimension of the array's shape using slicing
# The result will have a shape of (3, 4)
result = nums[0]
print("\nAfter removing the first dimension of the shape of the said array:")
print(result.shape)
Sample Output:
Shape of the said array: (1, 3, 4) After removing the first dimension of the shape of the said array: (3, 4)
Explanation:
In the above exercise -
The NumPy code first creates a 3-dimensional array nums with shape (1, 3, 4).
print(nums.shape): The print() function prints the shape of the “nums” array.
new_array = np.squeeze(nums, axis=0): Here, the np.squeeze() function is used to remove the first dimension (axis=0) of the "nums" array. The result is assigned to the variable "new_array".
print(new_array.shape): Finally print() function prints the shape of the “new_array” which returns (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