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

如何解决Jupyter Notebook中“string indices must be integers”报错?

解决"string indices must be integers"报错的方法

这个报错的核心原因是变量bank并非pandas DataFrame,而是一个字符串。当你尝试用bank['marital']的方式索引时,Python会将其识别为字符串索引操作,要求传入整数位置参数,因此触发报错。

排查与解决步骤

  • 检查CSV读取代码,大概率是你没有用pandas正确加载数据集。比如错误写法:

    with open('bank.csv', 'r') as f:
        bank = f.read()
    

    这种方式读取的bank是字符串类型,而非DataFrame。

  • 正确的CSV加载方式需使用pandas的read_csv方法:

    import pandas as pd
    import matplotlib.pyplot as plt
    
    # 先正确加载数据集
    bank = pd.read_csv('你的CSV文件路径.csv')
    # 再执行绘图代码
    bank['marital'].value_counts().plot(kind='pie', autopct='%.2f') 
    plt.show()
    

额外验证手段

运行print(type(bank)),若输出为<class 'str'>,则确认是数据加载方式错误;若输出为<class 'pandas.core.frame.DataFrame'>,则检查marital列是否存在——执行print(bank.columns)查看所有列名,避免列名拼写错误(比如大小写、空格问题)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:01:07