Element-wise addition of two Masked arrays in NumPy
NumPy: Masked Arrays Exercise-7 with Solution
Write a NumPy program to perform element-wise addition of two masked arrays, maintaining the masks.
Sample Solution:
Python Code:
import numpy as np # Import NumPy library
# Create two regular NumPy arrays with some values
data1 = np.array([1, 2, np.nan, 4, 5])
data2 = np.array([5, np.nan, 2, 3, 1])
# Create masks to specify which values to mask (e.g., NaN values)
mask1 = np.isnan(data1)
mask2 = np.isnan(data2)
# Create masked arrays using the regular arrays and the masks
masked_array1 = np.ma.masked_array(data1, mask=mask1)
masked_array2 = np.ma.masked_array(data2, mask=mask2)
# Perform element-wise addition of the two masked arrays, maintaining the masks
result_array = np.ma.add(masked_array1, masked_array2)
# Print the original masked arrays and the resulting array
print("Masked Array 1:")
print(masked_array1)
print("\nMasked Array 2:")
print(masked_array2)
print("\nResulting Array after Element-wise Addition:")
print(result_array)
Output:
Masked Array 1: [1.0 2.0 -- 4.0 5.0] Masked Array 2: [5.0 -- 2.0 3.0 1.0] Resulting Array after Element-wise Addition: [6.0 -- -- 7.0 6.0]
Explanation:
- Import NumPy Library:
- Import the NumPy library to handle array operations.
- Create Regular Arrays:
- Define two NumPy arrays data1 and data2 with integer values, including some NaN values to be masked.
- Define the masks:
- Create Boolean mask arrays 'mask1' and 'mask2' where True indicates the values to be masked (e.g., NaN values).
- Create Masked Arrays:
- Use "np.ma.masked_array()" to create masked arrays 'masked_array1' and 'masked_array2' from the regular arrays and the masks.
- Perform element-wise addition:
- Use "np.ma.add()" to perform element-wise addition of the two masked arrays, maintaining the masks.
- Finally display the original masked arrays and the resulting 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 and count Masked elements in NumPy.
Next: Create a Masked array and Mask a row 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://w3resource.com/python-exercises/numpy/element-wise-addition-of-two-masked-arrays-in-numpy.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics