我有一个带有某些条件的数据框和一个计数器,该计数器在满足条件A时进行计数。
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
我希望每次条件变化时都不会重置计数。
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()
谢谢!
答案 0 :(得分:4)
为什么不
df['count']=df['condition'].eq('A').cumsum()
答案 1 :(得分:1)