For a dataframe as follows, I want to fill missing years (from 2015 to 2017) in each group of city
and district
; then calculate pct
by grouping by columns: city
, district
and year
, at last step, then display value
and pct
columns horizontally?
city district value year
0 sh a 2 2015
1 sh a 3 2016
2 sh b 5 2015
3 sh b 3 2016
4 bj c 4 2015
5 bj c 3 2017
What I have done by far:
1. Fill missing years, but not working yet:
rng = pd.date_range('2015', '2017', freq='YS').dt.year
df = df.apply(lambda x: x.reindex(rng, fill_value = 0))
2. Calculating pct
by grouping by city
and district
:
df['pct'] = df.sort_values('year').groupby(['city', 'district']).value.pct_change()
3. Displaying value
and pct
columns horizontally but the order is not I wanted:
df.pivot_table(columns='year', index=['city','district'], values=['value', 'pct'], fill_value='NaN').reset_index()
The output I get so far:
city district pct value
year 2015 2016 2017 2015 2016 2017
0 bj c NaN NaN -0.25 4.0 NaN 3
1 sh a NaN 0.5 NaN 2.0 3 NaN
2 sh b NaN -0.4 NaN 5.0 3 NaN
How could I get the expected result will be like this?
city district 2015 2016 2017
value pct value pct value pct
bj c 4 3
sh a 2 3 0.5
sh b 5 3 -0.4
Thank you.