pandas转置select - do沿着转置系列进行分析

时间:2016-08-02 16:40:30

标签: python pandas

如果仅转置transposerows

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

1 个答案:

答案 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