How to get indices of elements that are greater than a threshold in 2D NumPy array?

Learn, how to get indices of elements that are greater than a threshold in 2D NumPy array?
By Pranit Sharma Last updated : December 25, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose that we are given a 2D numpy array that contains some numerical values and we need to get the indices of those values which are greater than a threshold value (say 5).

Getting the indices of elements that are greater than a threshold in 2D NumPy array

For this purpose, we can use numpy.argwhere() method to return the indices of all the entries in an array matching a boolean condition.

We need to pass a condition that (arr > 5) inside argwhere() as a parameter and it will return the index of that value where the result is True.

Syntax

Below is the syntax of numpy.argwhere() method:

numpy.argwhere(a)

Where, a is an array-like input data.

Let us understand with the help of an example,

Python code to get indices of elements that are greater than a threshold in 2D NumPy array

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([[10,2,5],[59,13,1]])

# Display original array
print("Original array:\n",arr,"\n")

# Returning indices of values 
# greater than 5
res = np.argwhere(arr>5)

# Display result
print("Result:\n",res,"\n")

Output

Example: How to get indices of elements that are greater than a threshold in 2D NumPy array?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.