如何基于得分DataFrame为对阵DataFrame生成获胜者新列?
解决方法:为对阵DataFrame添加获胜者列
这问题在Pandas数据处理里很常见,我给你两种实用的实现思路,你可以根据数据规模和个人习惯选择:
方法一:利用字典映射快速查找得分(推荐大数据量场景)
这种方法先把队伍得分表转换成键值对字典,然后逐行比对得分,效率很高。
步骤代码:
import pandas as pd # 初始化你的两个DataFrame df_points = pd.DataFrame({ 'team': [1, 2, 5, 3, 4], 'points': [2.5, 3.2, 5.8, 2.8, 1.9] }) df_matches = pd.DataFrame({ 'team1': [1, 2, 3], 'team2': [5, 4, 1] }) # 将得分表转为 team: points 的字典映射 score_dict = df_points.set_index('team')['points'].to_dict() # 逐行比较两队得分,生成winner列 df_matches['winner'] = df_matches.apply( lambda row: row['team1'] if score_dict[row['team1']] > score_dict[row['team2']] else row['team2'], axis=1 ) print(df_matches)
输出结果:
team1 team2 winner 0 1 5 5 1 2 4 2 2 3 1 3
方法二:通过合并DataFrame实现(更直观,适合新手)
这种方法把得分表分别合并到对阵表的两队列上,直接比对得分列,逻辑更清晰。
步骤代码:
import pandas as pd import numpy as np # 初始化DataFrame(同上) df_points = pd.DataFrame({ 'team': [1, 2, 5, 3, 4], 'points': [2.5, 3.2, 5.8, 2.8, 1.9] }) df_matches = pd.DataFrame({ 'team1': [1, 2, 3], 'team2': [5, 4, 1] }) # 合并team1的得分 df_matches = df_matches.merge(df_points, left_on='team1', right_on='team', suffixes=('', '_t1')) # 合并team2的得分 df_matches = df_matches.merge(df_points, left_on='team2', right_on='team', suffixes=('_t1', '_t2')) # 用numpy.where判断获胜者 df_matches['winner'] = np.where(df_matches['points_t1'] > df_matches['points_t2'], df_matches['team1'], df_matches['team2']) # 保留需要的列 df_matches = df_matches[['team1', 'team2', 'winner']] print(df_matches)
两种方法对比:
- 方法一:字典映射的方式内存占用更低,处理百万级以上数据时速度优势明显。
- 方法二:合并的方式逻辑更直观,不需要额外理解字典映射,适合刚接触Pandas的开发者。
内容的提问来源于stack exchange,提问作者Akash Meghani
相关产品推荐
相关产品推荐

