w3resource

Select elements from 2D NumPy array using Boolean indexing

NumPy: Advanced Indexing Exercise-1 with Solution

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:

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

Previous: NumPy Advanced Indexing Home.
Next: Select elements from 1D NumPy array using integer Indexing

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://198.211.115.131/python-exercises/numpy/select-elements-from-2d-numpy-array-using-boolean-indexing.php