How to sort values in a pandas DataFrame?

Published on Aug. 22, 2023, 12:17 p.m.

To sort values in a pandas DataFrame, you can use the sort_values() method. Here’s an example:

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Bob', 'Charlie'],
        'Score': [85, 75, 90, 95, 80, 70],
        'Subject': ['Math', 'Math', 'Math', 'English', 'English', 'English']}

df = pd.DataFrame(data)

# Sort the DataFrame by the 'Score' column in descending order
sorted_df = df.sort_values('Score', ascending=False)

print(sorted_df)

This will output:

      Name  Score  Subject
3    Alice     95  English
2  Charlie     90     Math
0    Alice     85     Math
4      Bob     80  English
1      Bob     75     Math
5  Charlie     70  English

In the example above, we sorted the DataFrame by the ‘Score’ column in descending order by setting ascending=False. You can also sort on multiple columns by specifying a list of column names to the sort_values() method.

I hope this helps! Let me know if you have any other questions.

Tags: