w3resource

Select elements using Mask Indexing in 2D NumPy arrays


20. 2D Array & Mask Array for Subset Selection

Indexing with Masks:

Write a NumPy program that creates a 2D NumPy array and uses a mask array (boolean array) for indexing to select a subset of elements that match the mask criteria.

Sample Solution:

Python Code:

import numpy as np

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

# Define a mask array to select elements that are greater than 50
mask = array_2d > 50

# Use the mask array for indexing to select elements that match the mask criteria
selected_elements = array_2d[mask]

# Print the original array, the mask array, and the selected elements
print('Original 2D array:\n', array_2d)
print('Mask array (elements > 50):\n', mask)
print('Selected elements using the mask:\n', selected_elements)

Output:

Original 2D array:
 [[83 21 74 71  3]
 [55  2 86 46 33]
 [58 37 41 29 33]
 [45 79 99 81 87]
 [38 80 47 68 45]]
Mask array (elements > 50):
 [[ True False  True  True False]
 [ True False  True False False]
 [ True False False False False]
 [False  True  True  True  True]
 [False  True False  True False]]
Selected elements using the mask:
 [83 74 71 55 86 58 79 99 81 87 80 68]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create 2D NumPy Array:
    • Create a 2D NumPy array named array_2d with random integers ranging from 0 to 99 and a shape of (5, 5).
  • Define Mask Array:
    • Define a mask array to select elements in the array that are greater than 50.
  • Indexing with Mask:
    • Used the mask array for indexing to select elements from array_2d that match the mask criteria.
  • Print Results:
    • Print the original 2D array, the mask array, and the selected elements to verify the indexing operation

For more Practice: Solve these Related Problems:

  • Create a 2D array and construct a boolean mask to select all elements that are multiples of a given number.
  • Write a function that accepts a 2D array and a mask array, then returns the subarray of elements where the mask is True.
  • Implement a solution that uses a mask to filter out rows where the average value is below a certain threshold.
  • Test the mask indexing approach on a 2D array and verify that the selected subarray matches the criteria defined by the mask.

Python-Numpy Code Editor:

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

Previous: Boolean Indexing on higher dimensions in NumPy arrays.

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.