w3resource

Mask values in NumPy array based on Complex condition

NumPy: Masked Arrays Exercise-17 with Solution

Write a NumPy program that creates a masked array from a regular array and mask values based on a complex condition.

Sample Solution:

Python Code:

import numpy as np
import numpy.ma as ma

# Create a 2D NumPy array of shape (5, 5) with random integers
array_2d = np.random.randint(0, 100, size=(5, 5))

# Define a complex condition to mask elements: values less than 20 or greater than 80
condition = (array_2d < 20) | (array_2d > 80)

# Create a masked array from the 2D array using the complex condition
masked_array = ma.masked_array(array_2d, mask=condition)

# Print the original array and the masked array
print('Original 2D array:\n', array_2d)
print('Masked array (values < 20 or > 80 are masked):\n', masked_array)

Output:

Original 2D array:
 [[23 56 52 73 24]
 [70 13 78 19 65]
 [41 67 51 94 93]
 [ 2 70 32 64 55]
 [37 75  1 54 35]]
Masked array (values < 20 or > 80 are masked):
 [[23 56 52 73 24]
 [70 -- 78 -- 65]
 [41 67 51 -- --]
 [-- 70 32 64 55]
 [37 75 -- 54 35]]

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:
    • Created a 2D NumPy array named 'array_2d' with random integers ranging from 0 to 99 and a shape of (5, 5).
  • Define Complex Condition:
    • Defined a complex condition to mask elements: values less than 20 or greater than 80 using logical OR (|).
  • Create Masked Array:
    • Create a masked array from the 2D array using ma.masked_array, applying the complex condition as the mask. Elements less than 20 or greater than 80 are masked.
  • Print the original 2D array and the masked array to verify the operation.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Perform Masked sum operation in NumPy ignoring Masked elements.
Next: Update Mask in NumPy Masked array to include additional elements.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/mask-values-in-numpy-array-based-on-complex-condition.php