w3resource

Create a Masked array and count Masked elements in NumPy

NumPy: Masked Arrays Exercise-6 with Solution

Write a NumPy program to create a masked array and count the number of masked elements.

Sample Solution:

Python Code:

import numpy as np  # Import NumPy library

# Create a regular NumPy array with some values
data = np.array([1, 2, np.nan, 4, 5, np.nan, 7, 8, 9, 10])

# Create a mask to specify which values to mask (e.g., NaN values)
mask = np.isnan(data)

# Create a masked array using the regular array and the mask
masked_array = np.ma.masked_array(data, mask=mask)

# Count the number of masked elements in the masked array
num_masked_elements = np.ma.count_masked(masked_array)

# Print the original array, the masked array, and the number of masked elements
print("Original Array:")
print(data)

print("\nMasked Array:")
print(masked_array)

print("\nNumber of Masked Elements:")
print(num_masked_elements)

Output:

Original Array:
[ 1.  2. nan  4.  5. nan  7.  8.  9. 10.]

Masked Array:
[1.0 2.0 -- 4.0 5.0 -- 7.0 8.0 9.0 10.0]

Number of Masked Elements:
2

Explanation:

  • Import NumPy Library:
    • Import the NumPy library to handle array operations.
  • Create a Regular Array:
    • Define a NumPy array with integer values and include some NaN values to be masked.
  • Define the Mask:
    • Create a Boolean mask array where True indicates the values to be masked (e.g., NaN values).
  • Create the Masked Array:
    • Use "np.ma.masked_array()" to create a masked array from the regular array and the mask.
  • Count Masked Elements:
    • Use “np.ma.count_masked()” to count the number of masked elements in the masked array.
  • Finally print the original array, the masked array, and the number of masked elements to verify the operation.

Python-Numpy Code Editor:

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

Previous: Replace Masked values with Mean in NumPy Masked array.
Next: Element-wise addition of two Masked arrays in NumPy.

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://198.211.115.131/python-exercises/numpy/create-a-masked-array-and-count-masked-elements-in-numpy.php