1

I would like to sort the col2 in descending order based on col1. I have the feeling that the answer is very simple, but I can't find a correct way. I would appreciate a lot some help.

The dataframe looks like:

Col1 Col2 Col3 
AB   5    Blue
AB   1    Red
AB   2    Green
AC   1    Red
AC   4    Blue
AD   9    Red
AD   5    Blue
AD   7    Green

The desired output:

Col1 Col2 Col3 
 AB   5    Blue
 AB   2    Green
 AB   1    Red
 AC   4    Blue
 AC   1    Red
 AD   9    Red
 AD   7    Green
 AD   5    Blue

What I tried:

df = pd.read_csv('data.csv')
df.sort_values(['Col1','Col2'], ascending = False)
df.groupby(['Col1'])['Col2'].sort_values(ascending = False)

None of the above methods gives the desired output.

1 Answer 1

2

Do:

print(df.sort_values(['Col1', 'Col2'], ascending=[True, False]))

Output

  Col1  Col2   Col3
0   AB     5   Blue
2   AB     2  Green
1   AB     1    Red
4   AC     4   Blue
3   AC     1    Red
5   AD     9    Red
7   AD     7  Green
6   AD     5   Blue

From the documentation on sort_values:

ascending : bool or list of bool, default True

Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.