Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas change order of columns in pivot table

The representation of pivot tabel not looks like something I looking for, to be more specific the order of the resulting rows. I can`t figure out how to change it in proper way.

Example df:

test_df = pd.DataFrame({'name':['name_1','name_1','name_1','name_2','name_2','name_2','name_3','name_3','name_3'], 
                        'month':[1,2,3,1,2,3,1,2,3], 
                        'salary':[100,100,100,110,110,110,120,120,120], 
                        'status':[1,1,2,1,1,3,2,2,1]})

code for make pivot:

test_df.pivot_table(index='name', columns=['month'], 
             values=['salary', 'status'])

Actual output:

       salary           status      
month       1    2    3      1  2  3
name                                
name_1    100  100  100      1  1  2
name_2    110  110  110      1  1  3
name_3    120  120  120      2  2  1

The output I want to see:

       salary status salary status salary status             
month       1     1      2      2      3      3
name
name_1    100     1     100     1     100     2
name_2    110     1     110     1     110     3
name_3    120     2     120     2     120     1
like image 361
cbccbd Avatar asked Mar 29 '19 11:03

cbccbd


3 Answers

You would use sort_index, indicating the axis and the level:

piv = test_df.pivot_table(index='name', columns=['month'], 
             values=['salary', 'status'])
piv.sort_index(axis='columns', level='month')
#       salary status salary status salary status
#month       1      1      2      2      3      3
#name                                            
#name_1    100      1    100      1    100      2
#name_2    110      1    110      1    110      3
#name_3    120      2    120      2    120      1
like image 111
Jondiedoop Avatar answered Oct 29 '22 13:10

Jondiedoop


Use DataFrame.sort_index with axis=1, level=1 arguments

(test_df.pivot_table(index='name', columns=['month'], 
             values=['salary', 'status'])
 .sort_index(axis=1, level=1))

[out]

       salary status salary status salary status
month       1      1      2      2      3      3
name                                            
name_1    100      1    100      1    100      2
name_2    110      1    110      1    110      3
name_3    120      2    120      2    120      1
like image 40
Chris Adams Avatar answered Oct 29 '22 13:10

Chris Adams


import pandas as pd

df = pd.DataFrame({'name': 
['name_1','name_1','name_1','name_2','name_2','name_2','name_3','name_3','name_3'], 
                        'month':[1,2,3,1,2,3,1,2,3], 
                        'salary':[100,100,100,110,110,110,120,120,120], 
                        'status':[1,1,2,1,1,3,2,2,1]})



df = df.pivot_table(index='name', columns=['month'], 
             values=['salary', 'status']).sort_index(axis='columns', level='month')
print(df) 
like image 40
Rajat Kansal Avatar answered Oct 29 '22 14:10

Rajat Kansal