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

全球恐怖主义数据集操作遇TypeError:列表索引需为整数/切片而非字符串

问题解决:TypeError: list indices must be integers or slices, not str
  • 核心原因:你用了**列表(list)**的索引方式去访问类似DataFrame的列,但data本身是Python原生列表,不是pandas的DataFrame。列表只能用整数位置索引(比如data[0]),不能用字符串列名['Year']。
  • 解决步骤:
    1. 先确认data的类型,执行代码:
      print(type(data))
      
      如果输出是<class 'list'>,说明确实是列表而非DataFrame。
    2. 若数据集是结构化表格,转换为pandas DataFrame:
      import pandas as pd
      data = pd.DataFrame(data)
      
      转换后再执行filterYear = data['Year'] == 1970即可正常运行。
    3. 若不想使用pandas,直接处理列表:
      假设列表内每个元素是包含Year字段的字典,用列表推导式筛选:
      filterYear = [item for item in data if item['Year'] == 1970]
      
  • 补充说明:你提到确认序列是数值型,应该是指列表中Year字段的值为数值类型,但这和索引方式无关——问题本质是data的类型不是DataFrame,导致无法用字符串索引列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:05:29