Related Articles
Get row numbers of NumPy array having element larger than X
• Last Updated : 11 Oct, 2020

Let’s see how to getting the row numbers of a numpy array that have at least one item is larger than a specified value X. So, for doing this task we will use numpy.where() and numpy.any() functions together.

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

Return: [ndarray or tuple of ndarrays] If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere.

Syntax: numpy.any(a, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c)

Return: [ndarray, optional]Output array with same dimensions as Input array, Placed with result

Example :

Arr = [[1,2,3,4,5],
[10,-3,30,4,5],
[3,2,5,-4,5],
[9,7,3,6,5]]
and X = 6 then output is [ 0, 2 ].

Here,
[[1,2,3,4,5],
no element is greater than 6 so output is [0].

[10,-3,30,4,5],
10 is greater than 6 so output is [0].

[3,2,5,-4,5],
no element is greater than 6 so output is [0, 2].

[4,7,3,6,5]]
7 is greater than 6 so output is [0, 2].

Below is the implementation:

## Python3

 # importing libraryimport numpy  # create numpy arrayarr = numpy.array([[1, 2, 3, 4, 5],                  [10, -3, 30, 4, 5],                  [3, 2, 5, -4, 5],                  [9, 7, 3, 6, 5]                  ])  # declare specified valueX = 6  # view arrayprint("Given Array:\n", arr)  # finding out the row numbersoutput  = numpy.where(numpy.any(arr > X,                                axis = 1))  # view outputprint("Result:\n", output)

Output:

Given 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], dtype=int64),)

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up