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

足球数据分析绘图遇TypeError:字符串索引必须为整数而非字符串

足球数据分析绘图报错:string indices must be integers, not 'str'

我正在进行足球数据分析,已基于两列条件生成子DataFrame,尝试在球场上绘制事件时触发错误:string indices must be integers, not 'str'。

所用DataFrame

typeIdoutcomexyendXendY
049136.759.60.00.0
11136.759.641.465.1
21141.465.126.870.4
31126.870.428.740.3
41128.637.639.529.3
51139.529.330.838.8
61130.838.820.739.2
71120.739.221.285.5
81121.285.532.396.0
91145.296.271.593.5
101184.594.590.680.3
111190.680.394.295.2
121196.096.591.095.9
131187.696.772.578.0
141172.578.057.878.4
151157.878.472.089.7
161174.579.497.980.5
171198.680.387.936.0
1816189.937.10.00.0

执行代码

for event in df1:
    if event['typeId'] == 1:
        pitch.arrows(df1.x, df1.y, df1.endX, df1.endY, lw=1.0, color='green', zorder=1, ax=axs[0,0])
    elif event['type'] == 16:
        pitch.scatter(event.x, event.y, s=450, edgecolors='#b94b75', linewidths=0.6, c='white', marker='football', ax=axs[0,0])

报错信息

TypeError                                 Traceback (most recent call last)
Cell In[21], line 20
     18 # Plot the events
     19 for event in df1:
---> 20     if event['typeId'] == 1:
     21         pitch.arrows(df1.x, df1.y, df1.endX, df1.endY, lw=1.0, color='green', zorder=1, ax=axs[0,0])
     22     elif event['type'] == 16:

TypeError: string indices must be integers, not 'str'

问题原因与解决方法

核心问题

直接for event in df1遍历的是DataFrame的列名(字符串类型),而非每一行数据。所以event['typeId']本质是对字符串用字符串索引,自然触发类型错误。

方法1:用iterrows()遍历行

这是最直接的修正方式,遍历每一行的索引和数据:

for idx, event in df1.iterrows():
    if event['typeId'] == 1:
        # 注意:这里要传单条数据的x/y,而非整个列
        pitch.arrows(event.x, event.y, event.endX, event.endY, lw=1.0, color='green', zorder=1, ax=axs[0,0])
    elif event['typeId'] == 16:  # 原代码里的type是笔误,应该是typeId
        pitch.scatter(event.x, event.y, s=450, edgecolors='#b94b75', linewidths=0.6, c='white', marker='football', ax=axs[0,0])

方法2:向量式操作(更高效)

Pandas不推荐逐行循环,建议直接筛选数据后批量绘图,效率更高:

# 筛选typeId=1的行,批量绘制箭头
passes = df1[df1['typeId'] == 1]
pitch.arrows(passes.x, passes.y, passes.endX, passes.endY, lw=1.0, color='green', zorder=1, ax=axs[0,0])

# 筛选typeId=16的行,批量绘制散点
shots = df1[df1['typeId'] == 16]
pitch.scatter(shots.x, shots.y, s=450, edgecolors='#b94b75', linewidths=0.6, c='white', marker='football', ax=axs[0,0])

额外修正点

原代码中elif event['type'] == 16是笔误,DataFrame的列名是typeId,需改为event['typeId']。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 20:54:55