PythonPandas和日期和描述

2024-04-28 17:16:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python2.7。我有一个熊猫数据框,看起来像

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月store1 57.97
2016年12月store2 24.99
2017年1月store1 2.00
2017年1月store2 60.73

我已经写了下面的代码,每个月的总和,但我坚持如何合并描述列。在

^{pr2}$

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


Tags: 数据dbdatadaterawaccountdescriptionfr
2条回答

使用^{}datetimes转换为使用Year格式化{},并将Description列添加到groupby

df = df.groupby([df['Date'].dt.strftime('%b %Y'),'Description']).sum().reset_index()
print (df)
       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

如果需要Datetime,则只添加另一列Description

^{pr2}$

要在更新版本的pandas中删除警告,请使用^{}

df = df.groupby([pd.Grouper(freq="M"),'Description']).sum().reset_index()
print (df)
        Date Description  Amount
0 2016-12-31      store1   57.97
1 2016-12-31      store2   24.99
2 2017-01-31      store1    2.00
3 2017-01-31      store2   60.73

您可以groupbydt.month和{}。使用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

相关问题 更多 >