Home > OS >  How to sort dataframe columns baed on 2 indexes?
How to sort dataframe columns baed on 2 indexes?

Time:12-15

I have a data frame like this

df:
Index   C-1  C-2  C-3  C-4 ........
Ind-1    3    9    5    4
Ind-2    5    2    8    3
Ind-3    0    1    1    0
  .
  .

The data frame has more than a hundred columns and rows with whole numbers(0-60) as values.
The first two rows(indexes) have values in the range 2-12/
I want to sort the columns based on values in the first and second rows(indexes) in ascending order. I need not care about sorting in the remaining rows.

Can anyone help me with this

CodePudding user response:

pandas.DataFrame.sort_values
In the first argument you pass rows that you need sorting on, and than axis to sort through columns.

Mind that by placement has a priority. If you want to sort first by second row and than by the first, you should pass ['Ind-2','Ind-1'], this will have a different result.

df.sort_values(by=['Ind-1','Ind-2'],axis=1)
Output
       C-1  C-4  C-3  C-2
Index                    
Ind-1    3    4    5    9
Ind-2    5    3    8    2
Ind-3    0    0    1    1
  • Related