w3resource

Creating a Masked array in NumPy


NumPy: Masked Arrays Exercise-1 with Solution


Write a NumPy program that creates a masked array from a regular NumPy array with some specified values masked.

Sample Solution:

Python Code:

import numpy as np  # Import NumPy library

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

# Create a mask to specify which values to mask
mask = np.array([False, True, False, True, False, True, False, True, False, True])

# 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:")
print(masked_array)

Output:

Original Array:
[ 1  2  3  4  5  6  7  8  9 10]

Masked Array:
[1 -- 3 -- 5 -- 7 -- 9 --]

Explanation:

  • Import NumPy:
    • Import the NumPy library for numerical operations.
  • Create a Regular Array:
    • Define a NumPy array with integer values from 1 to 10.
  • Define the Mask:
    • Create a Boolean mask array where True indicates the values to be masked.
  • 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 and masked arrays.

Python-Numpy Code Editor: