What are the most important attributes of a Numpy array object?

This shot will discuss some of the most important and widely used attributes of a NumPy array object in Python. These are:

  • ndim: This attribute helps find the number of dimensions of a NumPy array. For example, 11 means that the array is 1D1D, 22 means that the array is 2D2D, and so on.
  • shape: This attribute returns the dimension of the array. It is a tuple of integers that indicates the size of your NumPy array. For example, if you create a matrix with n rows and m columns, the shape will be (n * m).
  • size: This attribute calculates the total number of elements present in the NumPy array.
  • dtype: This attribute helps to check what type of elements are stored in the NumPy array.
  • itemsize: This attribute helps to find the length of each element of NumPy array in bytes. For example, if you have integer values in your array, this attribute will return 88 as integer values and take 88-bits in memory.
  • data: This attribute is a buffer object that points to the start of the NumPy array. However, this attribute isn’t used much because we usually access the elements in the array using indices.

Code

import numpy as np
first_array = np.array([1,2,3])
second_array = np.array([[1,2,3],[4,5,6]])
print("Frst array is: :",first_array)
print("Second array is: ",second_array)
print("\nNo. of dimension of First array: ",first_array.ndim)
print("No. of dimension of Second array: ",second_array.ndim)
print("\nShape of array First array: ",first_array.shape)
print("Shape of array Second array: ",second_array.shape)
print("\nSize of First array: ",first_array.size)
print("Size of Second array: ",second_array.size)
print("\nData type of First array: ",first_array.dtype)
print("Data type of Second array: ",second_array.dtype)
print("\nItemsize of First array: ",first_array.itemsize)
print("Itemsize of First array: ",second_array.itemsize)
print("\nData of First array is: ",first_array.data)
print("Data of Second array is: ",second_array.data)
Important attributes of NumPy array in Python

Explanation

  • On line 1, we import the package.
  • On lines 3 and 4, we create two NumPy arrays (one is a 1D array and the other is a 2D array) to see the outputs of the attributes that we just discussed.
  • On lines 6 and 7, we print both the arrays.
  • On lines 9 and 10, we use the dim attribute on both arrays.
  • On lines 12 and 13, we use the shape attribute on both arrays.
  • On lines 15 and 16, we use the size attribute on both arrays.
  • On lines 18 and 19, we use the dtype attribute on both arrays.
  • On lines 21 and 22, we use the itemsize attribute on both arrays.
  • On lines 24 and 25, we use the data attribute on both arrays.

Free Resources