So my dataframe looks like this:
from pandas.compat import StringIO
d = StringIO('''
date,site,country,score
2018-01-01,google,us,100
2018-01-01,google,ch,50
2018-01-02,google,us,70
2018-01-03,google,us,60
2018-01-02,google,ch,10
2018-01-01,fb,us,50
2018-01-02,fb,us,55
2018-01-03,fb,us,100
2018-01-01,fb,es,100
2018-01-02,fb,gb,100
''')
df = pd.read_csv(d, sep=",")
Each site
has a different score depending on the country
. I'm trying to find the 1/3/5-day difference of score
s for each site
/country
combination.
Output should be:
date,site,country,score,1_day_diff
2018-01-01,google,ch,50,0
2018-01-02,google,ch,10,-40
2018-01-01,google,us,100,0
2018-01-02,google,us,70,-30
2018-01-03,google,us,60,-10
2018-01-01,fb,es,100,0
2018-01-02,fb,gb,100,0
2018-01-01,fb,us,50,0
2018-01-02,fb,us,55,5
2018-01-03,fb,us,100,45
I first tried sorting by site
/country
/date
, then grouping by site
and country
but I'm not able to wrap my head around getting a difference from a grouped object.
io
- Alexes
andgb
would appear beforeus
. - Craigdf.sort_values(by=['site', 'country', 'date'], ascending=[False, True, True])
with @ayhan 's answer - akhilsp