Perform Masked sum operation in NumPy ignoring Masked elements
NumPy: Masked Arrays Exercise-16 with Solution
Write a NumPy program to create a masked array and perform a masked sum operation, ignoring the masked elements.
Sample Solution:
Python Code:
import numpy as np
import numpy.ma as ma
# Create a 2D NumPy array of shape (4, 4) with random integers
array_2d = np.random.randint(0, 100, size=(4, 4))
# Define the condition to mask elements greater than 50
condition = array_2d > 50
# Create a masked array from the 2D array using the condition
masked_array = ma.masked_array(array_2d, mask=condition)
# Perform a masked sum operation, ignoring the masked elements
masked_sum = masked_array.sum()
# Print the original array, the masked array, and the result of the masked sum
print('Original 2D array:\n', array_2d)
print('Masked array (elements > 50 are masked):\n', masked_array)
print('Sum of unmasked elements:', masked_sum)
Output:
Original 2D array: [[56 18 40 43] [61 87 68 74] [51 40 3 14] [51 63 49 90]] Masked array (elements > 50 are masked): [[-- 18 40 43] [-- -- -- --] [-- 40 3 14] [-- -- 49 --]] Sum of unmasked elements: 207
Explanation:
- Import Libraries:
- Imported numpy as "np" for array creation and manipulation.
- Imported numpy.ma as "ma" for creating and working with masked arrays.
- Create 2D NumPy Array:
- Create a 2D NumPy array named 'array_2d' with random integers ranging from 0 to 99 and a shape of (4, 4).
- Define Condition:
- Define a condition to mask elements in the array that are greater than 50.
- Create Masked Array:
- Create a masked array from the 2D array using ma.masked_array, applying the condition as the mask. Elements greater than 50 are masked.
- Perform Masked Sum:
- Use the sum method of the masked array to compute the sum of the unmasked elements, ignoring the masked elements.
- Print the original 2D array, the masked array, and the result of the masked sum.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Extract Unmasked data from a Masked NumPy array.
Next: Mask values in NumPy array based on Complex condition.
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://www.w3resource.com/python-exercises/numpy/perform-masked-sum-operation-in-numpy-ignoring-masked-elements.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics