深度阅读

How to sort values in a pandas DataFrame?

作者
作者
2023年08月22日
更新时间
9.93 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。