我有一个数据框 df,其中包含一段时间内的金融交易。我已将 df 重新索引为每笔交易的日期。
Description Amount Category
date
2018-12-03 Stop & Shop $100.00 Groceries
2018-12-03 Shell $50.00 Gas
2018-12-02 NYC Parking $25.00 Auto
2018-12-01 Tonys Pizza $14.00 Dining
2018-11-30 Dr Jones $100.00 Medical
我试图按月份和费用类别对这些数据进行分组。例如:
Auto Dining Gas Groceries Medical
Dec-2018 $25.00 $14.00 $50.00 $100.00 $100.00
Nov-2018 $35.00 $72.00 $40.00 $125.00 $0.00
...
Jan-2018
我试图通过使用“groupby”和“Resample.agg”按类别和月份累积交易来实现这一点,但不知道如何操作生成的数据框“输出”以我希望的格式显示输出为了。
output = df.groupby('Category').resample('M').agg({"Amount":'sum'})
感谢任何帮助。
请您参考如下方法:
pd.pivot_table + groupby + pd.Grouper
您可以将系列值转换为列标签,然后 groupby:
df = pd.pivot_table(df, index=df.index, columns='Category', values='Amount')\
.groupby(pd.Grouper(freq='M')).sum().fillna(0)
print(df)
Category Auto Dining Gas Groceries Medical
2018-11-30 0.0 0.0 0.0 0.0 100.0
2018-12-31 25.0 14.0 50.0 100.0 0.0
pd.crosstab + to_period
您还可以通过交叉表执行上述操作:
df = pd.crosstab(df.index.to_period('M'), columns=df['Category'],
values=df['Amount'], aggfunc='sum').fillna(0).rename_axis(None)
print(df)
Category Auto Dining Gas Groceries Medical
2018-11 0.0 0.0 0.0 0.0 100.0
2018-12 25.0 14.0 50.0 100.0 0.0
设置
df = pd.DataFrame({'Amount': [100.0, 50.0, 25.0, 14.0, 100.0],
'Category': ['Groceries', 'Gas', 'Auto', 'Dining', 'Medical'],
'Description': ['Stop&Shop', 'Shell', 'NYCParking', 'TonysPizza', 'DrJones']},
index=pd.to_datetime(['2018-12-03', '2018-12-03', '2018-12-02', '2018-12-01', '2018-11-30']))
