如何按Account与年份分组求和Pandas DataFrame并保留年末日期
问题描述
我有一个名为df的Pandas DataFrame,结构如下:
| Account | Type | Date | Per | Value |
|---|---|---|---|---|
| A | FC | 31/03/2019 | 3M | a |
| A | FC | 30/06/2019 | 3M | b |
| A | FC | 30/09/2019 | 3M | c |
| A | FC | 31/12/2019 | 3M | d |
| B | P&G | 31/03/2019 | 3M | e |
| B | P&G | 30/06/2019 | 3M | f |
| B | P&G | 30/09/2019 | 3M | g |
| B | P&G | 31/12/2019 | 3M | h |
其中a、b、c、d、e、f、g、h为数值。需要按Account列分组,对同一年份的Value列求和,同时结果中Date列取该分组对应年份的最后一个周期日期,最终得到如下结果:
| Account | Type | Date | Per | Value |
|---|---|---|---|---|
| A | FC | 31/12/2019 | 3M | a+b+c+d |
| B | P&G | 31/12/2019 | 3M | e+f+g+h |
我尝试了以下代码,但结果不符合需求:
test_df = pd.DataFrame(df.groupby('Date').sum().reset_index())
解决方案
实现代码
import pandas as pd # 转换Date列为日期类型,方便处理年份和排序 df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y') # 提取年份作为分组辅助列 df['Year'] = df['Date'].dt.year # 分组聚合:按Account和Year分组,指定各列的聚合规则 result_df = df.groupby(['Account', 'Year'], as_index=False).agg( Type=('Type', 'first'), Date=('Date', 'last'), Per=('Per', 'first'), Value=('Value', 'sum') ) # 将Date列转回原格式(dd/mm/yyyy) result_df['Date'] = result_df['Date'].dt.strftime('%d/%m/%Y') # 删除临时的Year列 result_df = result_df.drop('Year', axis=1) print(result_df)
代码说明
- 日期类型转换:把
Date列转为日期类型,避免字符串排序的误差,同时能准确提取年份和判断每组的最后日期。 - 分组逻辑:按
Account+Year分组,确保同一账号同一年的数据被聚合。 - 聚合规则:
Type和Per:同一账号下值固定,用first或last提取均可;Date:用last获取该年份最后一个周期的日期;Value:用sum完成数值求和。
- 格式还原:把
Date列转回原字符串格式,删除临时的Year列,得到符合需求的结果。
内容的提问来源于stack exchange,提问作者Valeria Arango
相关产品推荐
相关产品推荐

