Tony
Tony

Reputation: 1393

How to search for number of values greater than given values for each row

For example,

a = np.array([[1,2,3]
              [1,0,4]
              [2,1,1]])

and then for each row I would find the number of values greater than a corresponding value in another array, say b = np.array([2,1,0]), and the expected result is an array [1,1,3] (first row, one number greater than 2, second row, one number greater than 1, and the third row three numbers greater than 0).

Is there a way to use numpy build-in methods to achieve this? Many thanks!

Upvotes: 2

Views: 970

Answers (1)

Divakar
Divakar

Reputation: 221504

Extend b to 2D with None/np.newaxis such that each element is in one row. Then compare against a, which will broadcast those comparisons across all columns for each row and then sum rows -

In [12]: (a > b[:,None]).sum(axis=1)
Out[12]: array([1, 1, 3])

Upvotes: 4

Related Questions