w3resource

Select elements from 2D NumPy array using Boolean indexing


Boolean Indexing:

Write a NumPy program that creates a 2D NumPy array of random integers. Use boolean indexing to select all elements greater than a specified value.

Sample Solution:

Python Code:

import numpy as np

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

# Specify the value for boolean indexing
threshold = 50

# Use boolean indexing to select elements greater than the threshold
selected_elements = array_2d[array_2d > threshold]

# Print the original array and the selected elements
print('Original 2D array:\n', array_2d)
print(f'\nElements greater than {threshold}:\n', selected_elements)

Output:

Original 2D array:
 [[54 61 87 29 81]
 [60 54 32  5 45]
 [55 53 28 48  9]
 [ 2 72 47 20 35]
 [71 42 93 56 59]]

Elements greater than 50:
 [54 61 87 81 60 54 55 53 72 71 93 56 59]

Explanation:

  • Import Libraries:
    • Imported numpy as np for array creation and manipulation.
  • Create 2D NumPy Array:
    • Created a 5x5 NumPy array of random integers ranging from 0 to 99 using np.random.randint.
  • Specify Threshold:
    • Set a threshold value of 50 to use for boolean indexing.
  • Boolean Indexing:
    • Applied boolean indexing to select all elements in the array that are greater than the threshold value.
  • Print Results:
    • Printed the original 2D array and the elements that were selected based on the boolean condition.

Python-Numpy Code Editor: