基于Pandas按赛季统计切尔西黄牌与犯规总数的实现
问题与解答
问题背景
现有一份足球赛事数据CSV文件,结构及示例如下:
Season HomeTeam AwayTeam HomeYellow AwayYellow HomeFoul AwayFoul 2000-01 Chelsea West Ham 1 2 19 14 2000-01 Bradford Chelsea 0 1 14 16 2000-01 Chelsea Arsenal 3 1 16 22 ... 2002-03 Chelsea Blackburn 2 1 11 12 2002-03 N.castle Chelsea 0 1 12 22 ... 2006-07 Watford Chelsea 1 3 18 9 2006-07 Chelsea Tottenham 2 1 13 11
需要实现两个统计需求:
- 按
Season字段分组,统计切尔西各赛季的黄牌总数,输出格式如下:
Season YellowCards 2000-01 5 2002-03 3 2006-07 5
- 同理统计切尔西各赛季的犯规总数,输出格式如下:
Season Fouls 2000-01 51 2002-03 33 2006-07 22
核心问题:实现上述需求的Pandas代码逻辑是否通用,仅需替换字段名即可复用?
解答
这个代码逻辑完全通用,只需要替换对应的字段标识就能复用,本质是统一的「筛选切尔西参赛记录→按赛季分组→累加对应主场/客场统计字段」逻辑。
通用代码模板
可以封装成一个函数,传入目标统计项的前缀(比如Yellow对应HomeYellow/AwayYellow,Foul对应HomeFoul/AwayFoul),就能一键生成统计结果:
import pandas as pd def calculate_chelsea_season_stats(df, stat_prefix): # 筛选切尔西参与的所有比赛 chelsea_matches = df[(df['HomeTeam'] == 'Chelsea') | (df['AwayTeam'] == 'Chelsea')] # 计算单场比赛切尔西的对应统计值 chelsea_matches['single_match_stat'] = chelsea_matches.apply( lambda row: row[f'Home{stat_prefix}'] if row['HomeTeam'] == 'Chelsea' else row[f'Away{stat_prefix}'], axis=1 ) # 按赛季分组求和并整理结果格式 result = chelsea_matches.groupby('Season')['single_match_stat'].sum().reset_index() # 根据统计项重命名结果列 result.rename(columns={'single_match_stat': f'{stat_prefix}Cards' if stat_prefix == 'Yellow' else 'Fouls'}, inplace=True) return result # 读取CSV数据 df = pd.read_csv('your_data.csv') # 调用函数统计黄牌 yellow_stats = calculate_chelsea_season_stats(df, 'Yellow') print(yellow_stats) # 调用函数统计犯规 foul_stats = calculate_chelsea_season_stats(df, 'Foul') print(foul_stats)
逻辑说明
- 筛选逻辑固定:只保留切尔西作为主场或客场的比赛记录
- 字段匹配逻辑固定:根据切尔西的场边身份,自动匹配对应的主场/客场统计字段
- 分组求和逻辑固定:按
Season字段分组后,对单场统计值求和 - 唯一需要调整的就是
stat_prefix参数,传入Yellow或Foul即可切换统计项,无需修改核心逻辑。
内容的提问来源于stack exchange,提问作者Suj
相关产品推荐
相关产品推荐

