gpt4 book ai didi

python - 如何对 Pandas 中的连续记录(例如 "gaps and islands")进行分组?

转载 作者:行者123 更新时间:2023-12-05 02:33:00 25 4
gpt4 key购买 nike

我的问题与 How to group by continuous records in SQL 相同,只有我需要 Pandas 中的解决方案。

给定一个df like

ID  Colour
------------
1 Red
2 Red
3 Red
4 Red
5 Red
6 Green
7 Green
8 Green
9 Green
10 Red
11 Red
12 Red
13 Red
14 Green
15 Green
16 Green
17 Blue
18 Blue
19 Red
20 Blue

我想把它分组到

color  minId
------------
Red 1
Green 6
Red 10
Green 14
Blue 17
Red 19
Blue 20

可以更改颜色的名称(例如,Green1)

解决方案应该推广到其他聚合,而不仅仅是 min

最佳答案

您可以通过比较移位值和 cumsum 创建的助手系列按连续值分组,然后聚合 firstmin:

g = df['Colour'].ne(df['Colour'].shift()).cumsum()
df = df.groupby(g).agg(color=('Colour','first'), minId=('ID','min')).reset_index(drop=True)
print (df)
color minId
0 Red 1
1 Green 6
2 Red 10
3 Green 14
4 Blue 17
5 Red 19
6 Blue 20

关于python - 如何对 Pandas 中的连续记录(例如 "gaps and islands")进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71062411/

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