transpose
和rows
, columns
效果很好,但如何做transpose with selection
?
df = pd.DataFrame({'year': [2012,2013,2014, 2012,2013,2014], 'barber': ['Sue', 'Sue', 'Sue', 'Mike', 'Mike', 'Mike'], 'num_haircuts': [3,3,1,0,0,6]})
DF:
barber num_haircuts year
0 Sue 3 2012
1 Sue 3 2013
2 Sue 1 2014
3 Mike 0 2012
4 Mike 0 2013
5 Mike 6 2014
所需的df:
barber 2012 2013 2014
Sue 3 3 1
Mike 0 0 6
答案 0 :(得分:2)
使用pivot:
df.pivot(index='barber', columns='year', values='num_haircuts')
Out:
year 2012 2013 2014
barber
Mike 0 0 6
Sue 3 3 1