一、DataFrame数据排序
import pandas as pd
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Catherine', 'David'],
'score': [90, 80, 70, 85],
'age': [20, 19, 18, 22]})
print(df)
# 按照score列降序排列
df_sort = df.sort_values(by='score', ascending=False)
print(df_sort)
输出结果如下所示:
name score age
0 Alice 90 20
1 Bob 80 19
2 Catherine 70 18
3 David 85 22
name score age
0 Alice 90 20
3 David 85 22
1 Bob 80 19
2 Catherine 70 18
import pandas as pd
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Catherine', 'David'],
'score': [90, 80, 70, 85],
'age': [20, 19, 18, 22]})
print(df)
# 先按照score列降序排列,score相同再按照age升序排列
df_sort = df.sort_values(by=['score', 'age'], ascending=[False, True])
print(df_sort)
输出结果如下所示:
name score age
0 Alice 90 20
3 David 85 22
1 Bob 80 19
2 Catherine 70 18
name score age
0 Alice 90 20
3 David 85 22
1 Bob 80 19
2 Catherine 70 18
二、DataFrame数据排名
import pandas as pd
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Catherine', 'David'],
'score': [90, 80, 70, 85],
'age': [20, 19, 18, 22]})
print(df)
# 对score列进行升序排名
df_rank = df['score'].rank()
print(df_rank)
输出结果如下所示:
name score age
0 Alice 90 20
1 Bob 80 19
2 Catherine 70 18
3 David 85 22
0 4.0
1 3.0
2 1.0
3 2.0
Name: score, dtype: float64
import pandas as pd
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Catherine', 'David'],
'score': [90, 80, 70, 85],
'age': [20, 19, 18, 22]})
print(df)
# 先按照score列降序排名,score相同再按照age升序排名
df_rank = df.sort_values(by=['score', 'age'], ascending=[False, True]).rank()
print(df_rank)
输出结果如下所示:
name score age
0 4.0 4.0 3.0
3 3.0 3.0 4.0
1 2.0 2.0 2.0
2 1.0 1.0 1.0
本文链接:http://task.lmcjl.com/news/17413.html