w3resource

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:

import numpy as np  # Import NumPy library

# Create a regular NumPy array
data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

# Specify the value above which elements will be masked
threshold_value = 5

# Create a mask where all elements greater than the specified value are masked
mask = data > threshold_value

# Create a masked array using the regular array and the mask
masked_array = np.ma.masked_array(data, mask=mask)

# Print the original array and the masked array
print("Original Array:")
print(data)

print("\nMasked Array (elements > 5 are masked):")
print(masked_array)

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.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Compute Mean of a Masked array ignoring Masked values in NumPy.
Next: Replace Masked values with Mean in NumPy Masked array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.