w3resource

Creating a Masked array in NumPy


1. Masked Array Creation

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to create a masked array from a 1D array by masking all occurrences of a specific value and verify the mask.
  • Write a Numpy program to generate a masked array from a 2D array by masking values below a given threshold.
  • Write a Numpy program to convert a regular array into a masked array by masking out even numbers.
  • Write a Numpy program to create a masked array from a random array by masking elements that are prime numbers.

Python-Numpy Code Editor:

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

Previous: NumPy Masked Array Home.
Next: Fill Masked values in NumPy array with specified number.

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.