如何在Pandas中基于多条件从kill列生成death列
给Pandas DataFrame新增death列的解决方案
需求说明
需要为包含player、opponent、kill、team、opponent_team、map、game_id、match_id字段的DataFrame新增death列:
death列的值来自**同一game_id**下满足以下所有匹配条件的行的kill值:- 当前行
player= 目标行opponent - 当前行
opponent= 目标行player - 当前行
team= 目标行opponent_team - 当前行
opponent_team= 目标行team
- 当前行
最优解决方案(高效匹配)
推荐使用pandas.merge()方法实现,该方法在大数据量下的效率远高于逐行遍历:
代码示例
import pandas as pd # 假设原数据存储在DataFrame df中 # 1. 创建用于匹配的临时表,重命名字段以对应反向匹配关系 match_df = df.rename( columns={ 'player': 'opponent_match', 'opponent': 'player_match', 'team': 'opponent_team_match', 'opponent_team': 'team_match', 'kill': 'death' } )[['game_id', 'opponent_match', 'player_match', 'opponent_team_match', 'team_match', 'death']] # 2. 按条件合并原表与临时表 result_df = pd.merge( df, match_df, left_on=['game_id', 'player', 'opponent', 'team', 'opponent_team'], right_on=['game_id', 'opponent_match', 'player_match', 'opponent_team_match', 'team_match'], how='left' ) # 3. 清理临时字段并处理空值 result_df = result_df.drop(columns=['opponent_match', 'player_match', 'opponent_team_match', 'team_match']) # 无匹配记录时death设为0,可根据需求改为pd.NA result_df['death'] = result_df['death'].fillna(0)
代码解释
- 临时表重命名:将原表字段转换为反向匹配所需的命名,让合并条件更直观。
- 左连接合并:
how='left'确保原表所有行都被保留,不会丢失数据。 - 空值处理:没有对应反向击杀记录的行,
death默认设为0,可根据业务需求调整为pd.NA或其他值。
备选方案(逐行匹配,适合小数据集)
如果数据集规模较小,也可以用apply()逐行查找匹配,但效率较低:
def get_death(row): # 构建匹配条件 mask = ( (df['game_id'] == row['game_id']) & (df['opponent'] == row['player']) & (df['player'] == row['opponent']) & (df['opponent_team'] == row['team']) & (df['team'] == row['opponent_team']) ) matched_kills = df.loc[mask, 'kill'] # 返回匹配到的kill值,无匹配则返回0 return matched_kills.iloc[0] if not matched_kills.empty else 0 # 新增death列 df['death'] = df.apply(get_death, axis=1)
内容的提问来源于stack exchange,提问作者Octa
相关产品推荐
相关产品推荐

