Get the total bytes consumed by the elements in Numpy

To get the total bytes consumed by the masked array, use the ma.MaskedArray.nbytes attribute in Numpy. Does not include memory consumed by non-element attributes of the array object.

A mask is either nomask, indicating that no value of the associated array is invalid, or an array of booleans that determines for each element of the associated array whether the value is valid or not.

Steps

At first, import the required library −

import numpy as np
import numpy.ma as ma

Create an array using the numpy.array() method −

arr = np.array([[35, 85], [67, 33]])
print("Array...
", arr) print("\nArray type...
", arr.dtype) print("\nArray itemsize...
", arr.itemsize)

Get the dimensions of the Array −

print("Array Dimensions...
",arr.ndim)

Get the total bytes consumed −

print("Array nbytes...
",arr.nbytes)

Create a masked array and mask some of them as invalid −

maskArr = ma.masked_array(arr, mask =[[0, 0], [ 0, 1]])
print("\nOur Masked Array
", maskArr) print("\nOur Masked Array type...
", maskArr.dtype)

Get the dimensions of the Masked Array −

print("\nOur Masked Array Dimensions...
",maskArr.ndim)

Get the itemsize of the Masked Array −

print("\nOur Masked Array itemsize...
", maskArr.itemsize)

Get the total bytes consumed by the masked array, use the ma.MaskedArray.nbytes attribute in Numpy −

print("\nOur Masked Array nbytes...
",maskArr.nbytes)

Example

import numpy as np
import numpy.ma as ma
arr = np.array([[35, 85], [67, 33]])
print("Array...
", arr) print("\nArray type...
", arr.dtype) print("\nArray itemsize...
", arr.itemsize) # Get the dimensions of the Array print("Array Dimensions...
",arr.ndim) # Get the total bytes consumed print("Array nbytes...
",arr.nbytes) # Create a masked array and mask some of them as invalid maskArr = ma.masked_array(arr, mask =[[0, 0], [ 0, 1]]) print("\nOur Masked Array
", maskArr) print("\nOur Masked Array type...
", maskArr.dtype) # Get the dimensions of the Masked Array print("\nOur Masked Array Dimensions...
",maskArr.ndim) # Get the itemsize of the Masked Array print("\nOur Masked Array itemsize...
", maskArr.itemsize) # To get the total bytes consumed by the masked array, use the ma.MaskedArray.nbytes attribute in Numpy print("\nOur Masked Array nbytes...
",maskArr.nbytes)

Output

Array...
[[35 85]
[67 33]]

Array type...
int64

Array itemsize...
8
Array Dimensions...
2
Array nbytes...
32

Our Masked Array
[[35 85]
[67 --]]

Our Masked Array type...
int64

Our Masked Array Dimensions...
2

Our Masked Array itemsize...
8

Our Masked Array nbytes...
32
Updated on: 2022-02-22T06:40:43+05:30

716 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements