You need to enable JavaScript to run this app. Python使用Pandas按年份与球员名称分组求和Yds字段的问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Python使用Pandas按年份与球员名称分组求和Yds字段的问题求助

实现方案

1. 按年份+球员维度分组统计Yds总和

直接使用pandas内置的groupby聚合方法即可完成需求,无需自定义循环计数:

import pandas as pd

# 读取数据逻辑保持不变
df = pd.read_csv('D:RunningBackYards_3.csv', 
                 usecols=['Player', 'Tm', 'Year', 'Yds'])

# 按Year、Player两个维度分组,对Yds求和
player_year_yds = df.groupby(['Year', 'Player'], as_index=False)['Yds'].sum()

输出的player_year_yds就是每个球员对应每一年的累计码数统计结果。

2. 筛选每年码数最高的球员

如果需要提取每年累计码数排名第一的球员,可以在上述结果基础上做二次分组筛选:

# 仅保留每年Yds最高的1条记录,自动忽略并列第一
year_top_player = player_year_yds.loc[player_year_yds.groupby('Year')['Yds'].idxmax()]

# 如果需要保留同年码数并列第一的所有球员,用以下逻辑
year_top_player_all = player_year_yds[player_year_yds['Yds'] == player_year_yds.groupby('Year')['Yds'].transform('max')]

3. 可视化示例

可直接用matplotlib绘制每年最高码数的统计图表,标注对应球员姓名:

import matplotlib.pyplot as plt

# 解决中文显示异常问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(16, 7))
bars = plt.bar(year_top_player['Year'].astype(str), year_top_player['Yds'])
# 给每个柱子添加球员姓名标注
for bar, player in zip(bars, year_top_player['Player']):
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2, height, player,
             ha='center', va='bottom', rotation=45, fontsize=8)

plt.xlabel('年份')
plt.ylabel('累计码数')
plt.title('1970-2020年每年累计码数最高球员统计')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

原有代码问题说明:你使用collections.Counter的逻辑是统计所有球员姓名中每个字符的出现次数,和统计Yds总和的需求完全不相关,pandas原生的分组聚合能力已经可以覆盖这类需求,无需自定义循环。

内容的提问来源于stack exchange,提问作者Lino

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 23:24:04