Apply custom function to Unmasked elements in a Masked NumPy array
14. Apply Custom Function to Unmasked Elements
Write a NumPy program that creates a masked array and applies a custom function only to the unmasked elements.
Sample Solution:
Python Code:
Output:
Original 2D array: [[21 56 25 76] [10 61 56 86] [74 65 89 87] [75 94 3 79]] Masked array (elements > 50 are masked): [[21 -- 25 --] [10 -- -- --] [-- -- -- --] [-- -- 3 --]] Result after applying custom function to unmasked elements: [[42 -- 50 --] [20 -- -- --] [-- -- -- --] [-- -- 6 --]]
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.
- Define Custom Function:
- Define a custom function custom_function that takes an input x and returns x * 2.
- Apply Custom Function to Unmasked Elements:
- Use ma.apply_along_axis to apply the custom function only to the unmasked elements in the masked array.
- Finally print the original 2D array, the masked array, and the result after applying the custom function to the unmasked elements.
For more Practice: Solve these Related Problems:
- Write a Numpy program to apply a custom lambda function only to the unmasked elements of a masked array.
- Write a Numpy program to apply a custom mathematical transformation to unmasked elements in a 2D masked array.
- Write a Numpy program to create a custom function and use np.ma.apply_along_axis to process only the unmasked data.
- Write a Numpy program to implement a custom ufunc that operates solely on unmasked elements and then reassemble the full array.
Go to:
Previous: Perform Masked multiplication on a Masked array in NumPy.
Next: Extract Unmasked data from a Masked NumPy array.
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.