您可以使用
set_index和
unstack:
df = pd.Dataframe(data)df.set_index(['year','country']).unstack('year')产量
rep sales year 2013 2014 2015 2016 2013 2014 2015 2016country fr None kyle claire None NaN 10.0 20.0 NaNuk kyle None None john 12.0 NaN NaN 10.0usa None None None john NaN NaN NaN 21.0
或者,
pivot_table与配合使用
aggfunc='first':
df.pivot_table(index='country', columns='year', values=['rep','sales'], aggfunc='first')
产量
rep sales year 2013 2014 2015 2016 2013 2014 2015 2016country fr None kyle claire None None 10 20 Noneuk kyle None None john 12 None None 10usa None None None john None None None 21
使用
aggfunc='first', 通过获取找到的第一个值对每个
(country, year, rep)或
(country, year,sales)组进行聚合。在您的情况下,似乎没有重复项,因此第一个值与唯一的值相同。



