对于如下数据框,我想在每组中填充缺失的年份(从 2015 年到 2017 年city)district; 然后pct通过按列分组计算:city,district和year, 在最后一步,然后水平显示value和pct列?
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
到目前为止我所做的:
1. 填补缺失的年份,但尚未工作:
rng = pd.date_range('2015', '2017', freq='YS').dt.year
df = df.apply(lambda x: x.reindex(rng, fill_value = 0))
2.按和pct分组计算:citydistrict
df['pct'] = df.sort_values('year').groupby(['city', 'district']).value.pct_change()
3. 水平显示value和pct列,但顺序不是我想要的:
df.pivot_table(columns='year', index=['city','district'], values=['value', 'pct'], fill_value='NaN').reset_index()
到目前为止我得到的输出:
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
我怎么能得到预期的结果会是这样?
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
青春有我
相关分类