Set multi column index in pandas

后端 未结 2 2034
难免孤独
难免孤独 2020-12-24 03:34

I make dataframe like this.

df = pd.DataFrame({
    \'class\' : [\'A\', \'A\', \'A\', \'A\', \'A\', \'B\', \'B\', \'B\', \'B\', \'B\'],
    \'number\' : [1,2         


        
相关标签:
2条回答
  • 2020-12-24 03:57

    I like @jezrael answer a lot, but just for completeness - you can also use pandas.DataFrame.pivot_table instead of set_index + unstack:

    >>> df.pivot_table(index='number', columns='class').swaplevel(axis=1).sort_index(1)
    class        A            B     
           english math english math
    number                          
    1           40   90      87   67
    2           21   20      89   89
    3           68   50      54   79
    4           89   30      21   45
    5           90   57      23   23
    
    0 讨论(0)
  • 2020-12-24 04:01

    I think you need set_index with unstack for reshaping, then swap levels in MultiIndex in columns by swaplevel and last sort columns by sort_index:

    df1 = df.set_index(['number','class']).unstack().swaplevel(0,1,1).sort_index(1)
    
    print (df1)
    class        A            B     
           english math english math
    number                          
    1           40   90      87   67
    2           21   20      89   89
    3           68   50      54   79
    4           89   30      21   45
    5           90   57      23   23
    

    Another solution with stack and unstack:

    print (df.set_index(['number','class']).stack().unstack([1,2]))
    class        A            B     
           english math english math
    number                          
    1           40   90      87   67
    2           21   20      89   89
    3           68   50      54   79
    4           89   30      21   45
    5           90   57      23   23
    
    0 讨论(0)
提交回复
热议问题