Replace Masked values with Mean in NumPy Masked array
NumPy: Masked Arrays Exercise-5 with Solution
Write a NumPy program to replace all masked values in a masked array with the mean of the unmasked elements.
Sample Solution:
Python Code:
import numpy as np # Import NumPy library
# Create a regular NumPy array with some NaN values
data = np.array([1, 2, 3, np.nan, 5, 6, np.nan, 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)
# Compute the mean of the unmasked elements
mean_value = masked_array.mean()
# Replace all masked values with the mean of the unmasked elements
filled_array = masked_array.filled(mean_value)
# Print the original array, the masked array, and the filled array
print("Original Array:")
print(data)
print("\nMasked Array:")
print(masked_array)
print("\nFilled Array (masked values replaced with mean):")
print(filled_array)
Output:
Original Array: [ 1. 2. 3. nan 5. 6. nan 8. 9. 10.] Masked Array: [1.0 2.0 3.0 -- 5.0 6.0 -- 8.0 9.0 10.0] Filled Array (masked values replaced with mean): [ 1. 2. 3. 5.5 5. 6. 5.5 8. 9. 10. ]
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 "masked_array.mean()" to compute the mean of the unmasked elements in the masked array.
- Replace Masked Values:
- Use masked_array.filled(mean_value) to replace all masked values with the computed mean of the unmasked elements.
- Finally display the original array, the masked array, and the filled array to verify the operation.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Create a Masked array with elements greater than a specified value.
Next: Create a Masked array and count Masked elements in NumPy.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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/replace-masked-values-with-mean-in-numpy-masked-array.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics