use*_*327 1 python group-by dataframe pandas pandas-groupby
我使用的是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'])
Run Code Online (Sandbox Code Playgroud)
我想按每个描述和月份求和,以便我的数据如下:
日期描述金额
2016年12月store1 57.97
2016年12月store2 24.99
2017年1月store1 2.00
Jan 2017 store2 60.73
我已经编写了下面的代码,按月汇总,但我仍然坚持如何合并Description列.
#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
Run Code Online (Sandbox Code Playgroud)
任何指导都将非常感谢.谢谢.
你可以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
Run Code Online (Sandbox Code Playgroud)