Compute Mean of a Masked array ignoring Masked values in NumPy
NumPy: Masked Arrays Exercise-3 with Solution
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.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics