How to count result rows in pandas dataframe?

I have a pandas DataFrame. I want to count the number of rows satisfying the condition.

data has 800 rows; data[data['cond'] == 1]returns a frame with 343 lines. I need to save the number of rows in a variable. How can i do this?

+4
source share
3 answers

IIUC, I think you can just do:

a = len(data[data['cond'] == 1])
+4
source

You can use shape:

a = data[data['cond'] == 1].shape[0]

I use time and it seems that both options are the same in large df(length 60k):

In [1399]: %timeit data[data['fld1'] == 1].shape[0]
100 loops, best of 3: 4.9 ms per loop

In [1400]: %timeit len(data[data['fld1'] == 1])
100 loops, best of 3: 4.91 ms per loop
+2
source

x = sum(data['cond'] == 1)

(data ['cond'] == 1) Series, , sum True 1 False 0.

x = len(data[data['cond'] == 1])

, , "".

0
source

Source: https://habr.com/ru/post/1627776/


All Articles