我将foll数据帧作为groupby操作的结果:
region year
1.0 2015.0 6.775457e+05
2016.0 6.819761e+05
2017.0 6.864065e+05
如何将其转换为foll:
region year val
1.0 2015.0 6.775457e+05
1.0 2016.0 6.819761e+05
1.0 2017.0 6.864065e+05
我尝试使用unstack(),但这不起作用
答案 0 :(得分:2)
您需要reset_index
才能将Series
转换为DataFrame
:
df = df.groupby(['region', 'year'])['val'].sum().reset_index(name='val')
print (df)
region year val
0 1.0 2015.0 677545.7
1 1.0 2016.0 681976.1
2 1.0 2017.0 686406.5
或者,如果按sum
汇总,mean
添加参数as_index=False
:
df = df.groupby(['region', 'year'], as_index=False)['val'].sum()
print (df)
region year val
0 1.0 2015.0 677545.7
1 1.0 2016.0 681976.1
2 1.0 2017.0 686406.5