Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy: Counting in a 2D array where an element satisfies a condition

I have a numpy array like below. I need a count of rows where the first element is 2. So in the array below, four rows start with 2 - the answer would be 4. How is this best accomplished in numpy? (I cannot use pandas, but can use scipy).

array([[1, 4, 5],
       [1, 4, 5],
       [2, 4, 5],
       [2, 4, 5],
       [2, 4, 5],
       [2, 4, 5],
       [3, 4, 5],
       [3, 4, 5],
       [3, 4, 5],
       [3, 4, 5],
       [3, 4, 5],
       [3, 4, 5]])
like image 464
max_max_mir Avatar asked Feb 19 '26 17:02

max_max_mir


1 Answers

First, take the first column, all rows:

a[:,0]

Then, find the 2s:

a[:,0] == 2

That gives you a boolean array. Which you can then sum:

(a[:,0] == 2).sum()
like image 161
John Zwinck Avatar answered Feb 22 '26 07:02

John Zwinck