w3resource

Element-wise addition of two Masked arrays in NumPy


7. Element-wise Addition of Masked Arrays

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to perform element-wise addition of two masked arrays and ensure that the resulting mask is the union of the original masks.
  • Write a Numpy program to add two masked arrays and then fill the resulting masked positions with a default value.
  • Write a Numpy program to compare the result of adding two masked arrays with and without using np.ma.filled to handle missing data.
  • Write a Numpy program to perform addition on two masked arrays and then calculate the mean of the resulting array ignoring masked elements.

Go to:


Previous: Create a Masked array and count Masked elements in NumPy.
Next: Create a Masked array and Mask a row in NumPy.

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.