[英]% Difference Pivot Table python
I have a sample dataframe/table as below and I would like to do a simple pivot table in Python to calculate the % difference from the previous year.我有一个示例数据框/表格,如下所示,我想在 Python 中做一个简单的数据透视表来计算与上一年的差异百分比。
DataFrame
Year Month Count Amount Retailer
2019 5 10 100 ABC
2019 3 8 80 XYZ
2020 3 8 80 ABC
2020 5 7 70 XYZ
...
Expected Output预期产出
MONTH %Diff
ABC 7 -0.2
XYG 8 -0.125
Thanks,谢谢,
EDIT: I would like to reiterate that I would like to create the following table below.编辑:我想重申,我想创建下表。 Not to do a join with the two tables
不与两个表做连接
It looks like you need a groupby
not pivot
看起来你需要一个
groupby
而不是pivot
gdf = df.groupby(['Retailer']).agg({'Amount': 'pct_change'})
Then rename and merge with original df然后重命名并与原始 df 合并
df = gdf.rename(columns={'Amount': '%Diff'}).dropna().merge(df, how='left', left_index=True, right_index=True)
%Diff Year Month Count Amount Retailer
2 -0.200 2020 3 7 80 ABC
3 -0.125 2020 5 8 70 XYZ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.