# Convert the input to a masked array of the given data-type in Numpy

To convert the input to a masked array of the given data-type, use the numpy.ma.asarray() method in Python Numpy. No copy is performed if the input is already an ndarray. If the input data is a subclass of MaskedArray, a base class MaskedArray is returned.

The first parameter is the input data, in any form that can be converted to a masked array. The functions returns the Masked array interpretation of the first parameter. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists, ndarrays and masked arrays. The order parameter suggests whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'.

## 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([[65, 68, 81], [93, 33, 39], [73, 88, 51], [62, 45, 67]])
print("Array...", arr)
print("Array type...", arr.dtype)

Get the dimensions of the Array −

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


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

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

Get the dimensions of the Array 7minus;

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


Get the shape of the Array −

print("Our Masked Array Shape...",arr.shape)

Get the number of elements of the Array −

print("Elements in the Masked Array...",arr.size)


To convert the input to a masked array of the given data-type, use the numpy.ma.asarray() method −

print("Masked Array...",np.ma.asarray(arr))

Check the type −

print("Type...",type(np.ma.asarray(arr)))


## Example

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[65, 68, 81], [93, 33, 39], [73, 88, 51], [62, 45, 67]])
print("Array...", arr)
print("Array type...", arr.dtype)

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

# Create a masked array and mask some of them as invalid
maskArr = ma.masked_array(arr, mask =[[1, 1, 0], [ 0, 0, 0], [0, 1, 0], [0, 1, 0]])

# Get the dimensions of the Array

# Get the shape of the Array

# Get the number of elements of the Array

# To convert the input to a masked array of the given data-type, use the numpy.ma.asarray() method in Python Numpy

# Check the type
print("Type...",type(np.ma.asarray(arr)))

## Output

Array...
[[65 68 81]
[93 33 39]
[73 88 51]
[62 45 67]]

Array type...
int64

Array Dimensions...
2

[[-- -- 81]
[93 33 39]
[73 -- 51]
[62 -- 67]]

int64

2

(4, 3)

12

[[65 68 81]
[93 33 39]
[73 88 51]
[62 45 67]]

Type...
<class 'numpy.ma.core.MaskedArray'>

Updated on: 04-Feb-2022

467 Views