You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:15:29