Take difference between pivot table columns in Python

自闭症网瘾萝莉.ら 提交于 2021-02-10 14:15:20

问题


I have a dataframe with a Week , Campaign , Placement and Count column.

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)?

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!


回答1:


Use DataFrame.pct_change with selecting last row by positions and multiple by 100 for percentages:

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


来源:https://stackoverflow.com/questions/59159650/take-difference-between-pivot-table-columns-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!