0

Let's say I have the following dataframe:

  Priority   Color Risk
1        1   Green    8
2        9     Red   10
3        5  Orange    4
4        3   Green    8
5        3     Red   9
6        7  Orange    4

I would like to sort first on the 'color' column in the order of 'Red'> 'Orange'> 'Green'. Within that, I would like to sort on the 'priority' column in descending order (while maintaining the previous sort on the color column), and finally sort on the 'risk' column in descending order (while maintaining the previous sorts on the color and priority columns). So the result should look like this:

  Priority   Color Risk
2        9     Red   10
5        3     Red   9
6        7  Orange    4
3        5  Orange    4
4        3   Green    8
1        1   Green    8

Does anyone know how to do this?

Casper
  • 73
  • 6
  • Possible duplicate of [How to sort a dataFrame in python pandas by two or more columns?](https://stackoverflow.com/questions/17141558/how-to-sort-a-dataframe-in-python-pandas-by-two-or-more-columns) – G. Anderson Jul 22 '19 at 19:33

2 Answers2

0

just sort.

df.sort_values(['Color', 'Priority', 'Risk'],ascending=False)
DeepBlue
  • 415
  • 4
  • 9
0

If you transform color into a categorical variable, you can then define the order (which will be respected in any sorting).

df['Color'] = pd.Categorical(df['Color'], ["Red", "Orange", "Green"])
df.sort_values(['Color','Priority','Risk'], ascending=[True,False,False])

Out[1]: 
   Risk  Priority   Color
1    10         9     Red
4     9         3     Red
5     4         7  Orange
2     4         5  Orange
3     8         3   Green
0     8         1   Green

Some useful info on this answer too here

realr
  • 3,652
  • 6
  • 23
  • 34