Fadri
Fadri

Reputation: 157

Counting the number of rows that meet certain sum condition in pandas dataframe

I tried to get the number of rows when the total values of the first x rows in certain column in pandas dataframe exceed certain values. I've read several solutions, but not exactly what I am looking for. Basically I can do this with a loop as shown in the following codes. I just wondering whether there is any commando in python to do this without loop?

import pandas as pd

df = pd.DataFrame({'A': pd.Series(range(1, 10), index = \
                  range(1, len(range(1,10))+1))})
Count = 0

for i in df.loc[:, 'A']:
    Count += i
    if (Count > 5):
        break

print('Row index:', i)

this codes provides me what I want that the number of row when the sum of x first row in column A exceed 5 is three.

thanks

Upvotes: 1

Views: 477

Answers (1)

cs95
cs95

Reputation: 403218

cumsum + idxmax should work:

df.A.cumsum().gt(5).idxmax()

3

Upvotes: 2

Related Questions