w3resource

Compute Mean of a Masked array ignoring Masked values in NumPy


3. Mean of Masked Array

Write a NumPy program to compute the mean of a masked array, ignoring the masked values.

Sample Solution:

Python Code:

import numpy as np  # Import NumPy library

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

# Create a mask to specify which values to mask
mask = np.isnan(data)

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

# Compute the mean of the masked array, ignoring the masked values
mean_value = np.ma.mean(masked_array)

# Print the original array, the masked array, and the computed mean
print("Original Array:")
print(data)

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

print("\nMean of the Masked Array, Ignoring Masked Values:")
print(mean_value)

Output:

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

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

Mean of the Masked Array, Ignoring Masked Values:
5.444444444444445

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.
  • Compute the Mean:
    • Use np.ma.mean() to compute the mean of the masked array, ignoring the masked values.
  • Finally display the original array, the masked array, and the computed mean to verify the operation.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to compute the mean of a masked array while ignoring all masked values and compare it with np.ma.mean.
  • Write a Numpy program to calculate the mean of each row in a 2D masked array ignoring the masked entries.
  • Write a Numpy program to compute the column-wise mean of a masked array and handle columns with all values masked.
  • Write a Numpy program to compare the global mean of a masked array with a weighted mean that adjusts for the number of unmasked elements.

Go to:


Previous: Fill Masked values in NumPy array with specified number.
Next: Create a Masked array with elements greater than a specified value.

Python-Numpy Code Editor:

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

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.