Skip to content
Related Articles

Related Articles

Get row numbers of NumPy array having element larger than X

View Discussion
Improve Article
Save Article
Like Article
  • 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 library
import numpy
  
# create numpy array
arr = numpy.array([[1, 2, 3, 4, 5],
                  [10, -3, 30, 4, 5],
                  [3, 2, 5, -4, 5],
                  [9, 7, 3, 6, 5
                 ])
  
# declare specified value
X = 6
  
# view array
print("Given Array:\n", arr)
  
# finding out the row numbers
output  = numpy.where(numpy.any(arr > X,
                                axis = 1))
  
# view output
print("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),)
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!