w3resource

Create a Masked array with elements greater than a specified value

NumPy: Masked Arrays Exercise-4 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/create-a-masked-array-with-elements-greater-than-a-specified-value.php