NumPy ndarray.nbytes Attribute



The NumPy ndarray.nbytes attribute is used to get the total number of bytes consumed by the elements of a NumPy array. This attribute provides a quick way to determine the memory usage of an array.

It is particularly useful when working with large datasets and helps in understanding the overall memory consumption of the array, especially when performing memory management or optimization.

The nbytes attribute calculates the total memory usage by multiplying the number of elements in the array by the size of each element (using the itemsize attribute).

Usage of the nbytes Attribute in NumPy

The nbytes attribute can be accessed directly from a NumPy array object to calculate the total memory usage in bytes.

It is commonly used when analyzing large arrays, optimizing memory usage, or when estimating the storage requirements of a dataset.

Below are some examples that demonstrate how nbytes can be applied to various arrays in NumPy.

Example: Basic Usage of nbytes Attribute

In this example, we create a simple 1-dimensional array and use the nbytes attribute to find out the total memory usage of the array −

import numpy as np

# Creating a 1-dimensional array with integer elements
arr = np.array([1, 2, 3, 4])
print(arr.nbytes)

Following is the output obtained −

32

Example: Checking nbytes of a 2D Array

In this example, we create a 2-dimensional array and use the nbytes attribute to determine its total memory usage −

import numpy as np

# Creating a 2-dimensional array with float elements
arr = np.array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]])
print(arr.nbytes)

This will produce the following result −

48

Example: nbytes with Higher Dimensional Arrays

In this example, we create a 3-dimensional array and use the nbytes attribute to find out its total memory usage −

import numpy as np

# Creating a 3-dimensional array
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr.nbytes)

Following is the output of the above code −

64

Example: nbytes with Empty Arrays

In this example, we check the total memory usage of an empty array. This demonstrates that even an empty array has a memory overhead −

import numpy as np

# Creating an empty array
arr = np.array([])
print(arr.nbytes)

The output obtained is as shown below −

0
numpy_array_attributes.htm
Advertisements