w3resource

Find indices of Unmasked elements in Masked NumPy array


NumPy: Masked Arrays Exercise-11 with Solution


Write a NumPy program to create a masked array and find the indices of all unmasked 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)

# Find the indices of all unmasked elements
unmasked_indices = np.where(~masked_array.mask)

# Print the original array, the masked array, and the indices of unmasked elements
print('Original 2D array:\n', array_2d)
print('Masked array (elements > 50 are masked):\n', masked_array)
print('Indices of all unmasked elements:\n', unmasked_indices)

Output:

Original 2D array:
 [[20 22 83 86]
 [78 24 27 61]
 [76 84 53 76]
 [55 50  3 74]]
Masked array (elements > 50 are masked):
 [[20 22 -- --]
 [-- 24 27 --]
 [-- -- -- --]
 [-- 50 3 --]]
Indices of all unmasked elements:
 (array([0, 0, 1, 1, 3, 3], dtype=int64), array([0, 1, 1, 2, 1, 2], dtype=int64))

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 the 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.
  • Find Indices of Unmasked Elements:
    • Use np.where with the negation of the mask (~masked_array.mask) to find the indices of all unmasked elements.
  • Print the original 2D array, the masked array, and the indices of all unmasked elements.

Python-Numpy Code Editor: