[英]Take difference between pivot table columns in Python
I have a dataframe with a Week , Campaign , Placement and Count column.我有一个带有 Week 、 Campaign 、 Placement 和 Count 列的数据框。
In order to compare counts per weeks by Campaign and Placement I created a pivot table that works great.为了按活动和展示位置比较每周计数,我创建了一个非常有效的数据透视表。 How do I create a new column with the difference between these 2 weeks (in percentage if possible)?
如何创建具有这 2 周之间差异的新列(如果可能,以百分比表示)?
Code:代码:
dfPivot = pd.pivot_table(dfPivot, values='Count',\
index=['Campaign', 'Placement'],columns=['Week'], aggfunc=np.sum)
Current Output:电流输出:
Week 2019-10-27 2019-11-03
Campaign Placement Code
A 111111111 4288.0 615.0
111111112 243.0 11.0
111111113 598.0 30.0
111111114 1041.0 377.0
111111115 7759.0 161.0
B 111111111 1252.0 241.0
111111112 643.0 124.0
111111113 135.0 30.0
111111114 8753.0 2327.0
111111115 7242.0 112.0
Expected Output:预期输出:
Week 2019-10-27 2019-11-03 Difference
Campaign Placement Code
A 111111111 4288.0 615.0 -85.7%
111111112 243.0 11.0 -95.4%
111111113 598.0 30.0 -94.9%
111111114 1041.0 377.0 [...]
111111115 7759.0 161.0 [...]
B 111111111 1252.0 241.0 [...]
111111112 643.0 124.0 [...]
111111113 135.0 30.0 [...]
111111114 8753.0 2327.0 [...]
111111115 7242.0 112.0 [...]
Thank you!谢谢!
Use DataFrame.pct_change
with selecting last row by positions and multiple by 100
for percentages:使用
DataFrame.pct_change
按位置选择最后一行并乘以100
以获取百分比:
df['diff'] = df.pct_change(axis=1).iloc[:, -1].mul(100)
print (df)
2019-10-27 2019-11-03 diff
Campaign Placement Code
A 111111111 4288.0 615.0 -85.657649
111111112 243.0 11.0 -95.473251
111111113 598.0 30.0 -94.983278
111111114 1041.0 377.0 -63.784822
111111115 7759.0 161.0 -97.924990
B 111111111 1252.0 241.0 -80.750799
111111112 643.0 124.0 -80.715397
111111113 135.0 30.0 -77.777778
111111114 8753.0 2327.0 -73.414829
111111115 7242.0 112.0 -98.453466
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.