Get the Masked Array Dimensions in Numpy

NumpyServer Side ProgrammingProgramming

To get the dimensions of the Masked Array, use the ma.MaskedArray.ndim attribute in Python Numpy. 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.

NumPy offers comprehensive mathematical functions, random number generators, linear algebra routines, Fourier transforms, and more. It supports a wide range of hardware and computing platforms, and plays well with distributed, GPU, and sparse array libraries.

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...\n", arr)
print("\nArray type...\n", arr.dtype)
print("\nArray itemsize...\n", arr.itemsize)

Get the dimensions of the Array −

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

Get the total bytes consumed −

print("Array nbytes...\n",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\n", maskArr)
print("\nOur Masked Array type...\n", maskArr.dtype)

Get the itemsize of the Masked Array −

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

Get the dimensions of the Masked Array, use the ma.MaskedArray.ndim attribute in Numpy −

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

Example

import numpy as np
import numpy.ma as ma

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

# Get the dimensions of the Array
print("Array Dimensions...\n",arr.ndim)

# Get the total bytes consumed
print("Array nbytes...\n",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\n", maskArr)
print("\nOur Masked Array type...\n", maskArr.dtype)

# Get the itemsize of the Masked Array
print("\nOur Masked Array itemsize...\n", maskArr.itemsize)

# To get the dimensions of the Masked Array, use the ma.MaskedArray.ndim attribute in Numpy
print("\nOur Masked Array Dimensions...\n",maskArr.ndim)

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 itemsize...
8

Our Masked Array Dimensions...
2
raja
Updated on 17-Feb-2022 10:55:51

Advertisements