Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
808 views
in Technique[技术] by (71.8m points)

python - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why not

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...