Friday, October 24, 2025
HomeLanguagesNumpy MaskedArray.masked_invalid() function | Python

Numpy MaskedArray.masked_invalid() function | Python

In many circumstances, datasets can be incomplete or tainted by the presence of invalid data. For example, a sensor may have failed to record a data, or recorded an invalid value. The numpy.ma module provides a convenient way to address this issue, by introducing masked arrays.Masked arrays are arrays that may have missing or invalid entries.

numpy.MaskedArray.masked_invalid() function is used to mask an array where invalid values occur (NaNs or infs).This function is a shortcut to masked_where, with condition = ~(numpy.isfinite(arr)).

Syntax : numpy.ma.masked_invalid(arr, copy=True)

Parameters:
arr : [ndarray] Input array which we want to mask.
copy : [bool] If True (default) make a copy of arr in the result. If False modify arr in place and return a view.

Return : [ MaskedArray] The resultant array after masking.

Code #1 :




# Python program explaining
# numpy.MaskedArray.masked_invalid() method 
  
# importing numpy as geek 
# and numpy.ma module as ma
import numpy as geek
import numpy.ma as ma
  
# creating input array with invalid values
in_arr = geek.array([1, 2, geek.nan, -1, geek.inf])
print ("Input array : ", in_arr)
  
# applying MaskedArray.masked_invalid  
# methods to input array 
mask_arr = ma.masked_invalid(in_arr)
print ("Masked array : ", mask_arr)


Output:

Input array :  [ 1.  2. nan -1. inf]
Masked array :  [1.0 2.0 -- -1.0 --]

 

Code #2 :




# Python program explaining
# numpy.MaskedArray.masked_invalid() method 
  
# importing numpy as geek 
# and numpy.ma module as ma
import numpy as geek
import numpy.ma as ma
  
# creating input array with invalid element
in_arr = geek.array([5e8, 3e-5, geek.nan, 4e4, 5e2])
print ("Input array : ", in_arr)
  
# applying MaskedArray.masked_invalid  
# methods to input array 
mask_arr = ma.masked_invalid(in_arr)
print ("Masked array : ", mask_arr)


Output:

Input array :  [5.e+08 3.e-05    nan 4.e+04 5.e+02]
Masked array :  [500000000.0 3e-05 -- 40000.0 500.0]
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS