首页 > 解决方案 > Pandas - Evaluating row wise operation per entity

问题描述

I have a simple dataframe as shown below

Entity class   7dayAvg  10dayAvg
A      class1   50      100
A      class2   25      200
B      class1   40      80
B      class2   80      200

The problem at hand requires finding the percentage difference(7dayAvg and for 10dayAvg) between class1 and class2 for each entity A and B. Hence, the answer should be:

Entity  7day%Diff     10day%diff
A       (50-25)/50    (100-200)/100
B       (40-80)/40    (80-200)/80

标签: pythonpandasdataframe

解决方案


尝试groupby().pct_change()

df[['Entity']].join(-df.groupby('Entity')[['7dayAvg', '10dayAvg']]
                       .pct_change().dropna(),
                    how='inner')

输出:

  Entity  7dayAvg  10dayAvg
1      A      0.5      -1.0
3      B     -1.0      -1.5

推荐阅读