gpt4 book ai didi

python - Pandas Dataframe.groupby() 用于相同值的不同组

转载 作者:行者123 更新时间:2023-11-28 22:20:24 25 4
gpt4 key购买 nike

我有一个天气数据数据框,希望能够按季节对数据进行分组:

            yyyy  mm   rainfall  season
date
1941-01-01 1941 1 74.7 Winter
1941-02-01 1941 2 69.1 Winter
1941-03-01 1941 3 76.2 Spring
1941-04-01 1941 4 33.7 Spring
1941-05-01 1941 5 51.3 Spring
1941-06-01 1941 6 25.7 Summer
1941-07-01 1941 7 53.9 Summer
1941-08-01 1941 8 91.8 Summer
1941-09-01 1941 9 25.5 Autumn
1941-10-01 1941 10 106.2 Autumn
1941-11-01 1941 11 92.3 Autumn
1941-12-01 1941 12 86.5 Winter
1942-01-01 1942 1 114.0 Winter
1942-02-01 1942 2 13.8 Winter
1942-03-01 1942 3 58.0 Spring
1942-04-01 1942 4 42.5 Spring
1942-05-01 1942 5 101.1 Spring
1942-06-01 1942 6 2.3 Summer
1942-07-01 1942 7 70.2 Summer
1942-08-01 1942 8 78.5 Summer
1942-09-01 1942 9 146.8 Autumn
1942-10-01 1942 10 131.1 Autumn
1942-11-01 1942 11 19.8 Autumn
1942-12-01 1942 12 183.9 Winter

我将如何使用 df.groupby() 获得以下内容:

            season   rainfall  
date
1941-01-01 Winter [74.7, 69.1]
1941-03-01 Spring [76.2,33.7,51.3]
1941-06-01 Summer [25.7,53.9,91.8]
1941-09-01 Autumn [25.5,106.2,92.3]
1941-12-01 Winter [86.5,114.0,13.8]
1942-03-01 Spring [58.0,42.5,101.1]
1942-06-01 Summer [2.3,70.2,78.5]
1942-09-01 Autumn [146.8,131.1,19.8]
1942-12-01 Winter [183.9 ]

我试过 df.groupby(['season'])['rainfall'] 但它结合了每个冬天,而我只想对每个冬天的集群等进行分组。

最佳答案

目前 pandas 不直接支持这一点(参见问题 here ),但是有一些技巧可以做到这一点。

以下用于标记连续组,比较/转换是将每个季节与先前值进行比较以将更改标记为 1,然后 cumsum 为每个更改创建新组。

df['marker'] = (df['season'] != df['season'].shift()).cumsum()

从那里,你可以分组并做任何你想做的事——例如你的情况:

df.groupby('marker').agg({'date': 'first',  'season': 'first', 
'rainfall': lambda x: list(x)})
Out[14]:
date season rainfall
marker
1 1941-01-01 Winter [74.7, 69.1]
2 1941-03-01 Spring [76.2, 33.7, 51.3]
3 1941-06-01 Summer [25.7, 53.9, 91.8]
4 1941-09-01 Autumn [25.5, 106.2, 92.3]
5 1941-12-01 Winter [86.5, 114.0, 13.8]
6 1942-03-01 Spring [58.0, 42.5, 101.1]
7 1942-06-01 Summer [2.3, 70.2, 78.5]
8 1942-09-01 Autumn [146.8, 131.1, 19.8]
9 1942-12-01 Winter [183.9]

关于python - Pandas Dataframe.groupby() 用于相同值的不同组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48997350/

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