python - 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
解决方案
尝试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
推荐阅读
- asp.net - 在 Telerik 网格中显示总计
- javascript - 如何将 [object Map] 转换为车把中的可显示文本
- autodesk-forge - 翻译后删除源文件
- javascript - 如何在摩纳哥编辑器中监控文件是否从外部更改?
- elasticsearch - Elasticsearch Java API 将直接生成器添加到短语建议器
- reactjs - React Material UI 删除选定的单元格
- selenium-chromedriver - selenium chrome 驱动程序,在 URL 中收到“数据:”,并且无法打开正确的网页
- php - 刷新令牌到期日期
- angular - 从类型 T 更改为类型 Observable
在角 - android - RxBleConnection Observable 没有发射