所以我的数据框看起来像这样:
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
Each site
根据不同的情况有不同的分数country
。我正在尝试找出 1/3/5 天的差异score
s 为每个site
/country
组合。
输出应该是:
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
and country
但我无法集中精力从分组对象中找出差异。
首先,对 DataFrame 进行排序,然后你所需要的就是groupby.diff()
:
df = df.sort_values(by=['site', 'country', 'date'])
df['diff'] = df.groupby(['site', 'country'])['score'].diff().fillna(0)
df
Out:
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
sort_values
不支持任意排序。如果您需要任意排序(例如,Google 在 Facebook 之前),您需要将它们存储在集合中并将列设置为分类。然后 sort_values 将尊重您在那里提供的顺序。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)