1

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!

Tony
  • 1,225
  • 3
  • 12
  • 26

1 Answers1

3

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])
Divakar
  • 218,885
  • 19
  • 262
  • 358