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:

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.



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-masked-array-from-numpy-array.php