Open In App

Get Row Numbers of NumPy Array having Element Larger than X

Last Updated : 29 Sep, 2025
Suggest changes
Share
1 Likes
Like
Report

The task is to find the row indices of an array where at least one element is greater than a given threshold X.

For Example: Given array [[1, 5], [7, 2], [3, 9]] and X = 6 and goal is to identify the rows that contain values greater than 6.

Python
import numpy as np
arr = np.array([[1, 5], [7, 2], [3, 9]])
X = 6
res = np.where(np.any(arr > X, axis=1))
print(res)

Output
(array([1, 2]),)

Explanation:

  • arr > X creates a boolean array.
  • np.any(..., axis=1) checks each row for at least one value > 6.
  • np.where(...) gives row indices -> here rows 1 and 2.

Syntax

numpy.where()

numpy.where(condition[, x, y])

Parameters:

  • condition: Boolean expression to evaluate.
  • x, y (optional): Values to pick depending on whether the condition is True or False.

Return Value: Indices where condition holds true or array built from x and y.

numpy.any()

numpy.any(a, axis=None, out=None, keepdims=False)

Parameters:

  • a: Input array.
  • axis: Axis along which to evaluate condition (axis=1 checks row-wise).
  • out: Optional output array.
  • keepdims: Whether to keep reduced dimensions.

Return Value: Boolean result or array indicating if any condition is True.

Examples

Example 1: In this example, we create a 2D NumPy array and check which rows contain at least one element larger than a specified value X.

Python
import numpy as np
arr = np.array([[1, 2, 3, 4, 5],
                [10, -3, 30, 4, 5],
                [3, 2, 5, -4, 5],
                [9, 7, 3, 6, 5]])

X = 6  # declare threshold value
print("Array:")
print(arr)

res = np.where(np.any(arr > X, axis=1)) # find row numbers where at least one element > X
print("Result:")
print(res)

Output
Array:
[[ 1  2  3  4  5]
 [10 -3 30  4  5]
 [ 3  2  5 -4  5]
 [ 9  7  3  6  5]]
Result:
(array([1, 3]),)

Explanation

  • arr > X: Creates a boolean array marking values greater than X.
  • np.any(.., axis=1): Checks each row to see if at least one element is True.
  • np.where(...): Returns indices of rows where the condition holds.
  • Here, rows 1 and 3 contain elements larger than 6, so their indices are returned.

Example 2: In this example, we use a different 2D array and find rows that have elements larger than 15.

Python
import numpy as np
arr = np.array([[5, 8, 12], [20, 3, 9], [7, 14, 18], [2, 10, 6]])

X = 15   # declare threshold value
print("Array:")
print(arr)

res = np.where(np.any(arr > X, axis=1)) # find row numbers where at least one element > X
print("Result:")
print(res)

Output
Array:
[[ 5  8 12]
 [20  3  9]
 [ 7 14 18]
 [ 2 10  6]]
Result:
(array([1, 2]),)

Explanation:

  • arr > X: Marks elements greater than 15.
  • np.any(..., axis=1): Checks row-wise for any True.
  • np.where(...): Returns row indices with elements exceeding 15.
  • Rows 1 and 2 contain values above 15, so their indices are returned.

Explore