How to mask an array outside a given interval in NumPy
Overview
In NumPy, the masked_outside() function is used to mask an array outside a given interval.
Syntax
ma.masked_outside(x, v1, v2)
Syntax for the masked_outside() function
Parameters
This function takes the following parameter values:
x: This is the input array.v1andv2: These represent the boundary for which the values of the given array are not to be masked. Both values—v1andv2—are not included when masking.
Return value
This function returns a masked array with values within the specified intervals masked.
Example
# A code to illustrate the masked_inside() function# importing the necessary librariesimport numpy as npimport numpy.ma as ma# creating an input arraymy_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])# masking the values outside 3 to 7mask_array =ma.masked_outside(my_array, 3, 7)print(mask_array)
Explanation
- Line 4–5: We import the necessary library and module.
- Line 8: We create an input array,
my_array. - Line 11: We mask the values outside the interval of
3–7in the input array using themasked_outside()function. The result is assigned to a variable,mask_array. - Line 13: We print the value of the masked array,
mask_array.