gpt4 book ai didi

python - Pandas :根据条件计数分组

转载 作者:太空狗 更新时间:2023-10-30 02:24:45 25 4
gpt4 key购买 nike

我正在尝试根据每次不再满足条件时重置的累进计数对 Pandas (Python2.7) 中的数据帧进行分组。看起来像:

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 1
01,01,2018 08:07 B 2
01,01,2018 08:10 B 3
01,01,2018 08:13 B 4
01,01,2018 08:14 C 1
01,01,2018 08:16 C 2
01,01,2018 08:18 C 3
01,01,2018 08:20 C 4
01,01,2018 08:21 C 5
01,01,2018 08:22 A 1
01,01,2018 08:24 A 2
01,01,2018 08:25 B 1
01,01,2018 08:27 B 2
01,01,2018 08:29 B 3
01,01,2018 08:30 C 1

我正在尝试获取:

date                      condition        count   
01,01,2018 08:00 A 3
01,01,2018 08:04 B 4
01,01,2018 08:14 C 5
01,01,2018 08:22 A 2
01,01,2018 08:25 B 3
01,01,2018 08:30 C 1

如您所见,不可能仅按 A、B、C...分组,因为分组取决于条件正在变化这一事实,而不是条件本身。这就是我创建计数的原因,它可以帮助实现这一目的。我试过df2=df.groupby(['condition', 'date']).where(df['count']<df['count'].shift(1) , for周期...但我收到语法错误、定义错误或键错误,或“无法访问‘DataFrameGroupBy’对象的可调用属性‘where’,请尝试使用‘apply’方法”,以及许多其他错误,具体取决于尝试。

我希望你们中的一些人可以建议如何解决这个问题,在此先感谢您。

最佳答案

创建助手 Series 比较 shift通过 ne (!=) 使用 cumsum 编辑值然后按 agg 聚合与 firstlast :

g = df['condition'].ne(df['condition'].shift()).cumsum()
d = {'date':'first', 'condition':'first','count':'last'}
df = df.reset_index().groupby(g, as_index=False).agg(d)
print (df)
date condition count
0 01,01,2018 08:00 A 3
1 01,01,2018 08:04 B 4
2 01,01,2018 08:14 C 5
3 01,01,2018 08:22 A 2
4 01,01,2018 08:25 B 3
5 01,01,2018 08:30 C 1

关于python - Pandas :根据条件计数分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51835831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com