alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[895] Sort the rows of a DataFrame

In Pandas, the sort_values() method is used to sort the rows of a DataFrame by one or more columns. This method allows you to specify which column(s) to use for sorting and the sort order (ascending or descending). Here's how to use sort_values():

import pandas as pd
# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [25, 32, 18, 47, 22],
'Salary': [50000, 60000, 45000, 75000, 42000]}
df = pd.DataFrame(data)
# Sort the DataFrame by a single column (e.g., 'Age') in ascending order
sorted_df = df.sort_values(by='Age')
# To sort in descending order, use the 'ascending' parameter
sorted_df_desc = df.sort_values(by='Age', ascending=False)
# To sort by multiple columns, pass a list of column names
sorted_multi = df.sort_values(by=['Age', 'Salary'])
# Display the sorted DataFrames
print("Sorted by Age (ascending):")
print(sorted_df)
print("\nSorted by Age (descending):")
print(sorted_df_desc)
print("\nSorted by Age and Salary (both ascending):")
print(sorted_multi)

In this example:

  • We create a sample DataFrame df with columns 'Name', 'Age', and 'Salary'.
  • We use sort_values() to sort the DataFrame based on the 'Age' column. By default, it sorts in ascending order.
  • To sort in descending order, we pass the ascending=False parameter.
  • To sort by multiple columns, we pass a list of column names to the by parameter.

Here are the sorted DataFrames:

Sorted by Age (ascending):

Name Age Salary
2 Charlie 18 45000
0 Alice 25 50000
4 Eve 22 42000
1 Bob 32 60000
3 David 47 75000

Sorted by Age (descending):

Name Age Salary
3 David 47 75000
1 Bob 32 60000
0 Alice 25 50000
4 Eve 22 42000
2 Charlie 18 45000

Sorted by Age and Salary (both ascending):

Name Age Salary
2 Charlie 18 45000
4 Eve 22 42000
0 Alice 25 50000
1 Bob 32 60000
3 David 47 75000

You can adjust the sorting behavior by specifying the columns and sort order according to your needs.

posted on   McDelfino  阅读(8)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2022-10-10 【748】R语言相关材料
2019-10-10 【441】JSON format
2012-10-10 【084】◀▶ CSDN中的博客(VBA)
点击右上角即可分享
微信分享提示