如何在Pandas中处理多列并列情况实现自定义排名?
DataFrame多条件排名实现
需求说明
对包含20行数据的DataFrame生成1-20的唯一排名,规则如下:
- 主排序依据:
pontos_na_rodada(降序,数值越大排名越靠前) - 并列打破规则(依次生效):
saldo_gols(降序,数值越大越优)gols_feitos(降序,数值越大越优)Red Cards(升序,数值越小越优)Yellow Cards(升序,数值越小越优,缺失值视为最优)
数据示例
league_season league_round fixture_id team.id resultado 50885 2020 1.0 327986 118 3.0 46622 2020 1.0 327992 119 3.0 50863 2020 1.0 327986 120 0.0 60003 2020 1.0 327987 121 1.0 46637 2020 1.0 327991 123 3.0 46774 2020 1.0 327990 124 0.0 55991 2020 1.0 327994 126 3.0 46700 2020 1.0 327985 127 0.0 46730 2020 1.0 327988 128 1.0 46652 2020 1.0 327991 129 0.0 46758 2020 1.0 327990 130 3.0 50908 2020 1.0 327989 131 1.0 60024 2020 1.0 327987 133 1.0 46684 2020 1.0 327993 134 3.0 50931 2020 1.0 327989 144 1.0 46606 2020 1.0 327992 147 0.0 55970 2020 1.0 327994 151 0.0 46668 2020 1.0 327993 154 0.0 46743 2020 1.0 327988 794 1.0 46714 2020 1.0 327985 1062 3.0 gols_feitos saldo_gols Red Cards Yellow Cards pontos_na_rodada rank 50885 2.0 1.0 0.0 3.0 3.0 NaN 46622 1.0 1.0 0.0 4.0 3.0 NaN 50863 1.0 -1.0 1.0 2.0 0.0 NaN 60003 1.0 0.0 0.0 1.0 1.0 NaN 46637 3.0 1.0 0.0 3.0 3.0 NaN 46774 0.0 -1.0 0.0 3.0 0.0 NaN 55991 3.0 3.0 0.0 NaN 3.0 NaN 46700 0.0 -1.0 0.0 3.0 0.0 NaN 46730 1.0 0.0 0.0 NaN 1.0 NaN 46652 2.0 -1.0 0.0 3.0 0.0 NaN 46758 1.0 1.0 0.0 2.0 3.0 NaN 50908 0.0 0.0 0.0 2.0 1.0 NaN 60024 1.0 0.0 0.0 1.0 1.0 NaN 46684 2.0 2.0 0.0 2.0 3.0 NaN 50931 0.0 0.0 0.0 NaN 1.0 NaN 46606 0.0 -1.0 0.0 3.0 0.0 NaN 55970 0.0 -3.0 0.0 3.0 0.0 NaN 46668 0.0 -2.0 1.0 3.0 0.0 NaN 46743 1.0 0.0 0.0 1.0 1.0 NaN 46714 1.0 1.0 0.0 2.0 3.0 NaN
实现代码
import pandas as pd # 按规则排序 sorted_df = df.sort_values( by=['pontos_na_rodada', 'saldo_gols', 'gols_feitos', 'Red Cards', 'Yellow Cards'], ascending=[False, False, False, True, True], na_position='first' # 缺失值视为无牌,排在同条件前列 ) # 生成1-20的连续唯一排名 sorted_df['rank'] = range(1, len(sorted_df)+1) # 如需恢复原索引顺序,执行以下代码 df = sorted_df.sort_index()
代码说明
sort_values参数:by:严格按照需求的优先级指定排序列顺序ascending:对应列的排序方向,主列及前两个打破并列列用降序,红黄牌用升序na_position='first':处理Yellow Cards的缺失值,将其视为最优情况(无黄牌),排在同条件的前列
- 排名生成:直接用连续整数分配排名,确保每行有唯一的1-20排名
- 索引恢复:如果需要保持原始数据的索引顺序,最后按原索引重新排序即可
内容的提问来源于stack exchange,提问作者Vinícius Felizatti
相关产品推荐
相关产品推荐

