pandas :每次符合条件时计数器都会增加 [英] Pandas: counter increasing each time conditions are met

查看:43
本文介绍了 pandas :每次符合条件时计数器都会增加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有某些条件的数据框和一个计数器,该计数器在满足条件A时进行计数.

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

此刻,计数代码如下:

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

谢谢!

推荐答案

为什么不

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

这篇关于 pandas :每次符合条件时计数器都会增加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆