Home > Net >  Pandas - How to sort values in one column ascending and another column descending?
Pandas - How to sort values in one column ascending and another column descending?

Time:11-28

I have a dataframe with 2 columns. I'm trying to sort one column ('values') by descending order, and when two values are the same, sort another column by ascending order. Currently, my code is:

br_df = br_imgfeatures_df.mean().reset_index(name='value').sort_values(by='value', ascending=False)

Which is producing this output:

enter image description here

As you can see, the values for 'Palm trees' and 'Flowers' are the same, but I'm trying to reorder them with 'Flowers' on top of 'Palm trees'.

CodePudding user response:

Since pandas.DataFrame.sort_values accepts lists for the by parameter, you can use the code below and replace Column_X by the name of the first/other column :

br_df = (
            br_imgfeatures_df.mean()
                .reset_index(name='value')
                .sort_values(by=['value', 'Column_X'],
                             ascending=[False, True])
        )

# Output :

     Column_X     value
0   Nighttime  0.031496
1     Flowers  0.023622
2  Palm trees  0.023622
3       Cliff  0.020997
4      Bridge  0.018373
  • Related