[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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2022-10-10 【748】R语言相关材料
2019-10-10 【441】JSON format
2012-10-10 【084】◀▶ CSDN中的博客(VBA)