Pandas pivot table for multiple columns at once

后端 未结 3 678
无人及你
无人及你 2020-12-05 17:04

Let\'s say I have a DataFrame:

   nj  ptype  wd  wpt
0   2      1   2    1
1   3      2   1    2
2   1      1   3    1
3   2      2   3    3
4   3      1   2         


        
3条回答
  •  [愿得一人]
    2020-12-05 17:56

    Another solution using groupby and unstack.

    df2 = pd.concat([df.groupby(['ptype',e])[e].count().unstack() for e in ['nj','wd','wpt']],axis=1).fillna(0).astype(int)    
    df2.columns=pd.MultiIndex.from_product([['nj','wd','wpt'],[1.0,2.0,3.0]])
    
    df2
    Out[207]: 
           nj          wd         wpt        
          1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0
    ptype                                    
    1       1   1   1   0   2   1   2   1   0
    2       0   1   1   1   0   1   0   1   1
    

提交回复
热议问题