Return a view of the MaskedArray data in Numpy

NumpyServer Side ProgrammingProgramming

To return a view of the MaskedArray data in Numpy, use the ma.MaskedArray.view() method.

The a.view() is used two different ways

  • a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type. This can cause a reinterpretation of the bytes of memory.

  • a.view(ndarray_subclass) or a.view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array. This does not cause a reinterpretation of the memory.

Steps

At first, import the required library −

import numpy as np
import numpy.ma as ma

Create an array with int elements using the numpy.array() method −

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

Get the dimensions of the Array −

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

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

maskArr = ma.masked_array(arr, mask =[[0, 1], [ 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 −

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

Get the shape of the Masked Array −

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

Copying −

resArr = maskArr.copy()

Return a view of the MaskedArray data in Numpy, use the ma.MaskedArray.view() method −

print("\nView...\n",resArr.view())

Example

# Python ma.MaskedArray - Return a view of the MaskedArray data

import numpy as np
import numpy.ma as ma

# Create an array with int elements 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)

# Create a masked array and mask some of them as invalid
maskArr = ma.masked_array(arr, mask =[[0, 1], [ 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
print("\nOur Masked Array Dimensions...\n",maskArr.ndim)

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

# copying
resArr = maskArr.copy()

# To return a view of the MaskedArray data in Numpy, use the ma.MaskedArray.view() method in Numpy
print("\nView...\n",resArr.view())

Ouptut

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

Array type...
int64

Array itemsize...
8
Array Dimensions...
2

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

Our Masked Array type...
int64

Our Masked Array itemsize...
8

Our Masked Array Dimensions...
2

Our Masked Array Shape...
(2, 2)

View...
[[35 --]
[67 --]]
raja
Updated on 02-Feb-2022 06:43:42

Advertisements