NumPy: Get the number of items, array dimensions, number of array dimensions and the memory size of each element of a given array
Get array metadata (dimensions, size, etc.).
Write a NumPy program to get the number of items, array dimensions, number of array dimensions and the memory size of each element of a given array.
Sample Solution:
Python Code:
# Importing NumPy library
import numpy as np
# Creating a 2D NumPy array
array_nums = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# Printing the original array
print("Original array:")
print(array_nums)
# Finding the number of items in the array
print("\nNumber of items of the said array:")
print(array_nums.size)
# Retrieving the shape of the array (number of rows and columns)
print("\nArray dimensions:")
print(array_nums.shape)
# Finding the number of dimensions of the array
print("\nNumber of array dimensions:")
print(array_nums.ndim)
# Determining the memory size (in bytes) of each array element
print("\nMemory size of each element of the said array")
print(array_nums.itemsize)
Sample Output:
Original array: [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] Number of items of the said array: 12 Array dimensions: (3, 4) Number of array dimensions: 2 Memory size of each element of the said array 8
Explanation:
In the above code -
- array_nums = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) creates a 2-dimensional NumPy array with 3 rows and 4 columns.
- print(array_nums) prints the array.
- print(array_nums.size) prints the total number of elements in the array (3 rows * 4 columns = 12).
- print(array_nums.shape) prints the shape of the array as a tuple, in this case (3, 4), indicating 3 rows and 4 columns.
- print(array_nums.ndim) prints the number of dimensions (axes) of the array, which is 2 for a 2-dimensional array.
- print(array_nums.itemsize) prints the size (in bytes) of each element in the array.
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