Skip to content
Advertisement

pandas df – sort on index but exclude first column from sort

I want to sort this df on rows (‘bad job’) but I want to exclude the first column from the sort so it remains where it is:

          Radisson   Marriott   Hilton      IHG     
Category                                        
good job  0.214941   0.40394    0.448931    0.375316
bad  job  0.514941   0.10394    0.348931    0.475316
crap job  0.114941   0.20394    0.548931    0.175316

expected output:

          Radisson   IHG        Hilton     Marriott   
Category                                        
good job  0.214941   0.375316   0.448931   0.40394
bad  job  0.514941   0.475316   0.348931   0.10394 
crap job  0.114941   0.175316   0.548931   0.20394 

I don’t know to edit my code below to exclude the 1st column from the sort:

 df = df.sort_values(by=[df.index[1]], axis=1, ascending=False)

Advertisement

Answer

Use argsort with add 1 for possible add first value 0 by reindex for positions, last change columns order by iloc:

s = df.iloc[0]
df = df.iloc[:, ((-s[1:]).argsort() + 1).reindex(df.columns, fill_value=0)]
print (df)
          Radisson    Hilton  Marriott       IHG
Category                                                     
good job  0.214941  0.448931   0.40394  0.375316
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement