python - 绘制来自 Pandas 的某些数据点

标签 python pandas

我正在尝试构建一个处理棒球统计数据的程序。我要求用户输入一个团队,然后代码通过我创建的 Pandas 运行,搜索与用户输入匹配的“teamID”。

我试过按“teamID”分组,但在 for 循环之前进行索引。

def AttendancePlot(teams,team_pick):

    fig, ax = plt.subplots()
    group_by_teamID = teams.groupby(by=['teamID'])
    print group_by_teamID

    for i in group_by_teamID.index:
        if i == team_pick:
            ax.scatter(teams['yearID'][i], teams['attendance'][i], color="#4DDB94", s=200)
            ax.annotate(i, (teams['yearID'][i], teams['attendance'][i]),
               bbox=dict(boxstyle="round", color="#4DDB94"),
               xytext=(-30, 30), textcoords='offset points',
               arrowprops=dict(arrowstyle="->", connectionstyle="angle,angleA=0,angleB=90,rad=10"))

我是如何创造 Pandas 的

teams = pd.read_csv('Teams.csv')
salaries = pd.read_csv('Salaries.csv')
names = pd.read_csv('Names.csv')

teams = teams[teams['yearID'] >= 1985]
teams = teams[['yearID', 'teamID', 'Rank', 'R', 'RA', 'G', 'W', 'H', 'BB',    'HBP', 'AB', 'SF', 'HR', '2B', '3B', 'attendance']]
teams = teams.set_index(['yearID', 'teamID'])

salaries_by_yearID_teamID = salaries.groupby(['yearID', 'teamID'])  ['salary'].sum()
teams = teams.join(salaries_by_yearID_teamID)

print teams.head(15)

输出 Pandas

          Rank    R   RA    G     ...       2B  3B  attendance      salary
yearID teamID                          ...                                     
1985   ATL        5  632  781  162     ...      213  28   1350137.0   14807000.0
       BAL        4  818  764  161     ...      234  22   2132387.0  11560712.0
       BOS        5  800  720  163     ...      292  31   1786633.0  10897560.0
       CAL        2  732  703  162     ...      215  31   2567427.0  14427894.0

我想要一个散点图,显示某个输入团队的年度出勤率。我得到一个没有错误的空白图表。

最佳答案

这里不需要使用 groupby()groupby() 通常在您想对选定的行应用一些数学运算时使用。您需要的是正确选择数据。

此函数将绘制给定团队 team_pick 的年份(x 轴)与出勤率(y 轴),假设您使用的数据帧结构描述(数据框是 teams):

def AttendancePlot(teams, team_pick):
    teamdata = teams.loc[teams.index.get_level_values('teamID') == team_pick]
    plt.scatter(teamdata.index.levels[0], teamdata['attendance'])
    plt.show()

我给你留下注释。

关键是这一行:teamdata = teams.loc[teams.index.get_level_values('teamID') == team_pick]
teams.index.get_level_values('teamID') == team_pick 对多行索引执行选择,允许您选择团队为 team_pick 的所有行。
teamdata 因此是一个数据框,其中包含给定团队的所有行。

这叫做 pandas indexing .另见 pandas advanced indexing .

关于python - 绘制来自 Pandas 的某些数据点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56094705/

相关文章:

python - py2exe 没有正确编译 VideoCapture

python - Pandas:为太频繁或太稀有的值过滤数据框

python - 识别 pandas 系列中多个连续值为负数的周期

python - 如何将垂直列表转换为panda dataframe?

python - Paraview:更改渲染窗口中轴的纵横比

python - 使用 DRF 时 API 响应时间太慢

python - 是否可以在 Tkinter 下拉菜单中获取用户文本输入?如果是这样,怎么办?

python - for 每天同时循环 20 个数据帧

python - Pandas 字符串按可变长度位置过滤

python - 来自 MultiIndex 和 NumPy 结构化数组 (recarray) 的 Pandas DataFrame