Create a Masked array with elements greater than a specified value
4. Mask Elements Greater Than Specified Value
Write a NumPy program that creates a masked array where all elements greater than a specified value are masked.
Sample Solution:
Python Code:
Output:
Original Array: [ 1 2 3 4 5 6 7 8 9 10] Masked Array (elements > 5 are masked): [1 2 3 4 5 -- -- -- -- --]
Explanation:
- Import NumPy Library:
- Import the NumPy library to handle array operations.
- Create a Regular Array:
- Define a NumPy array with integer values from 1 to 10.
- Specify Threshold Value:
- Define the threshold value above which elements will be masked (e.g., 5).
- Create the Mask:
- Create a Boolean mask array where True indicates the values greater than the threshold value.
- Create the Masked Array:
- Use "np.ma.masked_array()" to create a masked array from the regular array and the mask.
- Finally display the original array and the masked array to verify the operation.
For more Practice: Solve these Related Problems:
- Write a Numpy program to create a masked array by masking all elements greater than a specified threshold in a 1D array.
- Write a Numpy program to mask elements in a 2D array that exceed a given value and then visualize the masked array.
- Write a Numpy program to generate a masked array from a random array where elements above the 75th percentile are masked.
- Write a Numpy program to mask elements greater than a computed dynamic threshold (e.g., mean plus one standard deviation) in an array.
Go to:
Previous: Compute Mean of a Masked array ignoring Masked values in NumPy.
Next: Replace Masked values with Mean in NumPy Masked array.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.