您可以使用^{}+^{}:df = df.set_index(['country','name','year'])['medals_won'].unstack(fill_value=0)
print (df)
year 2010 2011 2012 2013 2015
country name
AU jones 0 0 0 2 8
US alice 3 0 4 0 1
sarah 1 2 0 0 5
如果重复项需要聚合,如mean,sum。。。使用^{}或^{}+aggregate function+^{}:
^{pr2}$
或者:df = df.groupby(['country','name','year'])['medals_won'].mean().unstack(fill_value=0)
print (df)
year 2010 2011 2012 2013 2015
country name
AU jones 0.0 0.0 0.0 2.0 8.0
US alice 3.0 0.0 4.0 0.0 1.0
sarah 2.5 2.0 0.0 0.0 5.0
最后:df = df.reset_index().rename_axis(None, axis=1)
print (df)
country name 2010 2011 2012 2013 2015
0 AU jones 0 0 0 2 8
1 US alice 3 0 4 0 1
2 US sarah 1 2 0 0 5