【发布时间】:2018-06-29 01:44:03
【问题描述】:
所以我的数据框看起来像这样:
date site country score
0 2018-01-01 google us 100
1 2018-01-01 google ch 50
2 2018-01-02 google us 70
3 2018-01-03 google us 60
4 2018-01-02 google ch 10
5 2018-01-01 fb us 50
6 2018-01-02 fb us 55
7 2018-01-03 fb us 100
8 2018-01-01 fb es 100
9 2018-01-02 fb gb 100
每个site 都有不同的分数,具体取决于country。我正在尝试为每个 site/country 组合找到 scores 的 1/3/5 天差异。
输出应该是:
date site country score diff
8 2018-01-01 fb es 100 0.0
9 2018-01-02 fb gb 100 0.0
5 2018-01-01 fb us 50 0.0
6 2018-01-02 fb us 55 5.0
7 2018-01-03 fb us 100 45.0
1 2018-01-01 google ch 50 0.0
4 2018-01-02 google ch 10 -40.0
0 2018-01-01 google us 100 0.0
2 2018-01-02 google us 70 -30.0
3 2018-01-03 google us 60 -10.0
我首先尝试按site/country/date 进行排序,然后按site 和country 进行分组,但我无法集中精力从分组对象中获得差异。
【问题讨论】:
-
如何为 python3 获取 StringIO?我正在尝试重现您的问题
-
@JulianRachman 使用
io -
好的,等一下,我正在尝试重现您的问题
-
@Alex @ayhan 我已经编辑了预期的输出。本质上,
es和gb会出现在us之前。 -
@Craig 你可以添加
df.sort_values(by=['site', 'country', 'date'], ascending=[False, True, True])和@ayhan 的答案
标签: python pandas dataframe group-by