如何用Pandas或SQL方式统计玩家累计积分并找出最高积分玩家
完全可以用Pandas原生方法和SQL实现,两种方案的性能都远高于你现在用iterrows遍历的实现,尤其数据量较大时优势更明显。
实现方案
Pandas 原生实现
核心思路是把winner_id和loser_id拆成独立的玩家行,保留对应积分后分组汇总:
# 将winner和loser字段打平为玩家ID列 player_points = matches_df.melt( id_vars=["points"], value_vars=["winner_id", "loser_id"], value_name="player_id" ) # 按玩家ID分组求和累计积分 total_points = player_points.groupby("player_id")["points"].sum() # 获取总积分最高的玩家ID max_player_id = total_points.idxmax()
如果要同时拿到最高积分的数值,直接取total_points.max()即可。
SQL 实现
核心思路是用UNION ALL把获胜者、落败者的ID和对应积分合并后分组统计:
SELECT player_id, SUM(points) AS total_points FROM ( SELECT winner_id AS player_id, points FROM matches UNION ALL SELECT loser_id AS player_id, points FROM matches ) AS all_player_records GROUP BY player_id ORDER BY total_points DESC LIMIT 1;
内容的提问来源于stack exchange,提问作者jebaseelan ravi
相关产品推荐
相关产品推荐

