如何修复Pandas中生成足球比赛结果条件列的语法错误?
修复足球比赛结果判断的Pandas代码
原代码的错误点
- Python中不能直接将
if-elif-else流程语句赋值给变量,Pandas列操作需要用矢量化函数或apply方法实现批量判断 - 语法错误:
elif条件中Football_data_match['goal_scored'<...]缺少闭合方括号] - 语法错误:
Football_data_match['result'] 'lost'缺少赋值运算符= - 括号不匹配:开头的
if(没有正确闭合,且错误地将整个流程语句用括号包裹后赋值
正确代码实现(推荐矢量化方法)
使用numpy.select处理多条件判断,效率远高于循环或apply,适合大数据集:
import numpy as np import pandas as pd # 定义判断条件和对应结果 conditions = [ Football_data_match['goal_scored'] > Football_data_match['goal_against'], Football_data_match['goal_scored'] < Football_data_match['goal_against'], Football_data_match['goal_scored'] == Football_data_match['goal_against'] ] choices = ['win', 'lost', 'draw'] # 生成结果列 Football_data_match['result'] = np.select(conditions, choices)
备选方法:嵌套np.where(适合简单三条件)
Football_data_match['result'] = np.where( Football_data_match['goal_scored'] > Football_data_match['goal_against'], 'win', np.where( Football_data_match['goal_scored'] < Football_data_match['goal_against'], 'lost', 'draw' ) )
备选方法:apply(不推荐,小数据集可用)
def get_match_result(row): if row['goal_scored'] > row['goal_against']: return 'win' elif row['goal_scored'] < row['goal_against']: return 'lost' else: return 'draw' Football_data_match['result'] = Football_data_match.apply(get_match_result, axis=1)
内容的提问来源于stack exchange,提问作者Martijn
相关产品推荐
相关产品推荐

