Skip to main content
 首页 » 编程设计

Python Pandas 求和日期和描述

2025年05月04日12lori

我正在使用 Python 2.7。我有一个 Pandas 数据框,看起来像

raw_data = {'Date': ['12/1/2016', '12/4/2016','12/23/2016', '1/18/2017','1/18/2017','1/19/2017'],  
    'Account': ['aa1', 'aa2','aa1', 'aa1', 'aa1', 'aa2'],  
    'Description': ['store1', 'store2','store1', 'store2','store1','store2' ],  
    'Amount': [26.43, 24.99, 31.54,45.32, 2.00, 15.41], 
    'Category': ['G','G','G','G','G','G'], 
    'Initials': ['FR','DB','FR','DB','FR','FR']} 
df = pd.DataFrame(raw_data, columns = ['Date','Account','Description','Amount','Category','Initials']) 

我想按每个描述和月份进行汇总,以便我的数据如下所示:
日期 描述 金额
2016 年 12 月商店 1 57.97
2016 年 12 月 store2 24.99
2017 年 1 月 store1 2.00
2017 年 1 月 store2 60.73

我已经编写了以下按月求和的代码,但我对如何合并描述列感到困惑。

#convert Date to datetimeindex 
df['Date'] = pd.to_datetime(df['Date']) 
df = df.set_index('Date') 
 
#sum by month 
df = df.groupby(pd.TimeGrouper("M")).sum() 
df 

任何指导将不胜感激。谢谢。

请您参考如下方法:

您可以groupby dt.month 和Description。使用 dt.strftime 并将月份编号转换为月份名称,然后执行分组:

df.groupby([df.Date.dt.strftime('%b %Y'), 
       'Description']).Amount.sum().reset_index() 
 
       Date Description  Amount 
0  Dec 2016      store1   57.97 
1  Dec 2016      store2   24.99 
2  Jan 2017      store1    2.00 
3  Jan 2017      store2   60.73