我有一个dataframe写个排序函数sort fun,
时间: 2024-05-12 11:21:15 浏览: 186
解决DataFrame排序sort的问题
可以按照指定的列进行排序,也可以选择升序或降序排序。
以下是一个示例代码:
```python
import pandas as pd
def sort_fun(df, column, ascending=True):
"""Sorts a dataframe by a specified column.
Args:
df (pandas.DataFrame): The dataframe to be sorted.
column (str): The name of the column to sort by.
ascending (bool, optional): Whether to sort in ascending order (default True).
Returns:
pandas.DataFrame: The sorted dataframe.
"""
sorted_df = df.sort_values(by=column, ascending=ascending)
return sorted_df
```
使用示例:
```python
# create a sample dataframe
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
'Age': [23, 42, 31, 28, 35],
'Salary': [50000, 60000, 55000, 65000, 70000]}
df = pd.DataFrame(data)
# sort by Age in ascending order
sorted_df = sort_fun(df, 'Age')
print(sorted_df)
# sort by Salary in descending order
sorted_df = sort_fun(df, 'Salary', ascending=False)
print(sorted_df)
```
输出结果:
```
Name Age Salary
0 Alice 23 50000
3 David 28 65000
2 Charlie 31 55000
4 Eva 35 70000
1 Bob 42 60000
Name Age Salary
4 Eva 35 70000
3 David 28 65000
1 Bob 42 60000
2 Charlie 31 55000
0 Alice 23 50000
```
阅读全文