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: