Luca91
Luca91

Reputation: 609

Pandas: counter increasing each time conditions are met

I have a dataframe with some conditions and a Counter that Counts when condition A is met.

 date                      condition        count   
    01,01,2018 08:00             A               1
    01,01,2018 08:01             A               2
    01,01,2018 08:03             A               3
    01,01,2018 08:04             B               0
    01,01,2018 08:07             B               0
    01,01,2018 08:10             B               0
    01,01,2018 08:13             B               0
    01,01,2018 08:22             A               1
    01,01,2018 08:24             A               2
    01,01,2018 08:25             B               0
    01,01,2018 08:27             B               0
    01,01,2018 08:29             B               0
    01,01,2018 08:30             A               1

I would like that the Count doesn't reset each time condition changes.

date                      condition        count   
01,01,2018 08:00             A               1
01,01,2018 08:01             A               2
01,01,2018 08:03             A               3
01,01,2018 08:04             B               3
01,01,2018 08:07             B               3
01,01,2018 08:10             B               3
01,01,2018 08:13             B               3
01,01,2018 08:22             A               4
01,01,2018 08:24             A               5
01,01,2018 08:25             B               5
01,01,2018 08:27             B               5
01,01,2018 08:29             B               5
01,01,2018 08:30             A               6

At the Moment the code for the Count Looks like:

df['count']= df.groupby((df['condition'] = 'A').cumsum()).cumcount()

Thanks!

Upvotes: 2

Views: 743

Answers (2)

pizza lover
pizza lover

Reputation: 523

I think groupby.cumsum is what you're looking for

df['count']= df.groupby((df['Date']['condition']).cumsum())

and then later subset the df based on required condition.

Upvotes: 1

BENY
BENY

Reputation: 323386

Why not

df['count']=df['condition'].eq('A').cumsum()

Upvotes: 5

Related Questions