Select elements using Mask Indexing in 2D NumPy arrays
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
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics