Convert Masked Array elements to Float Type in Numpy

To convert masked array to float type, use the ma.MaskedArray.__float__() method in 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.

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([30])
print("Array...", arr)
print("\nArray type...", arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...",arr.ndim)

Create a masked array −

maskArr = ma.masked_array(arr, mask =[False])
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)

Convert masked array to float type, use the ma.MaskedArray.__float__() method in Numpy −

print("\nResult Converted to float type...
",maskArr.__float__())

Example

import numpy as np
import numpy.ma as ma

# Create an array using the numpy.array() method
arr = np.array([30])
print("Array...", arr)
print("\nArray type...", arr.dtype)

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

# Create a masked array
maskArr = ma.masked_array(arr, mask =[False])
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) # To convert masked array to float type, use the ma.MaskedArray.__float__() method in Numpy print("\nResult Converted to float type...
",maskArr.__float__())

Output

Array... [30]

Array type... int64

Array Dimensions... 1

Our Masked Array
[30]

Our Masked Array type...
int64

Our Masked Array Dimensions...
1

Result Converted to float type...
30.0
Updated on: 2022-02-22T06:55:10+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements