a concise shot of dev knowledge
Become a Contributor
Concise shots of dev knowledge

RELATED TAGS

numpy
communitycreator

How to mask an array where invalid values occur in NumPy

Onyejiaku Theophilus Chidalu

Overview

The masked_invalid() function in NumPy is used to mask an array where invalid values occur. These invalid values could be NaNs or infs.

Syntax

ma.masked_invalid(a)
Syntax for the masked_invalid() function

Parameters

The masked_invalid() function takes a single parameter value, a, which is an array.

Return value

The masked_invalid() function returns a masked array.

Example

# A code to illustrate the masked_invalid() function 

# importing the necessary libraries
import numpy as np
import numpy.ma as ma

# creating an input array
my_array = np.array([1, 2, 3, np.NaN, 5, 6, np.PINF, 8, 9, np.NaN])

# printing the array
print(my_array)

# masking the values greater than 2
mask_array =ma.masked_invalid(my_array, 2)

print(mask_array)
Implementing the masked_invalid() function

Explanation

  • Line 4–5: We import the necessary library and module.
  • Line 8: We create an input array, my_array, containing some invalid values.
  • Line 11: We print the input array, my_array.
  • Line 14: We mask the invalid values of the input array using the masked_invalid() function. The result is assigned to a variable, mask_array.
  • Line 16: We print the masked array, mask_array.

RELATED TAGS

numpy
communitycreator

CREATOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.

soc2