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

如何解决Python(Pandas DataFrame)中的TypeError: string indices must be integers, not 'list'

问题:Seaborn lmplot报错TypeError: string indices must be integers, not 'list'

问题场景

我在练习使用世界教育数据集时,导入数据集后用df.info()查看了数据类型,其中“Countries and areas”列为object类型,其余多为int64类型。之后想通过sns.lmplot查看Completion_Rate_Upper_Secondary_Male与Unemployment_Rate的关系,执行了以下代码:

global_education='global_education.csv'
sns.lmplot(x='Completion_Rate_Upper_Secondary_Male',y='Unemployment_Rate',data=global_education)

却触发了如下报错:

TypeError                                 Traceback (most recent call last)
Cell In[46], line 2
      1 global_education='global_education.csv'
----> 2     sns.lmplot(x='Completion_Rate_Lower_Secondary_Male',y='Unemployment_Rate',data=global_education)

 File ~\anaconda3\Lib\site-packages\seaborn\regression.py:595, in lmplot(data, x, y, hue, col, row, palette, col_wrap, height, aspect, markers, sharex, sharey, hue_order, col_order, row_order, legend, legend_out, x_estimator, x_bins, x_ci, scatter, fit_reg, ci, n_boot, units, seed, order, logistic, lowess, robust, logx, x_partial, y_partial, truncate, x_jitter, y_jitter, scatter_kws, line_kws, facet_kws)
    593 need_cols = [x, y, hue, col, row, units, x_partial, y_partial]
    594 cols = np.unique([a for a in need_cols if a is not None]).tolist()
--> 595 data = data[cols]
    597 # Initialize the grid
    598 facets = FacetGrid(
    599     data, row=row, col=col, hue=hue,
    600     palette=palette,
   (...)
    603     **facet_kws,
    604 )

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

错误原因与解决方法

  • 错误核心:你把文件名字符串'global_education.csv'直接传给了sns.lmplot的data参数,但这个参数要求传入的是已加载到内存的Pandas DataFrame对象,而不是文件路径字符串。Seaborn尝试对字符串进行data[cols]这种DataFrame式的索引操作,自然会报错“字符串索引必须是整数,不能是列表”。
  • 修复步骤:
    1. 先用Pandas加载CSV文件为DataFrame:
      import pandas as pd
      global_education = pd.read_csv('global_education.csv')
      
    2. 再调用sns.lmplot,此时传入的就是正确的DataFrame对象:
      import seaborn as sns
      sns.lmplot(x='Completion_Rate_Upper_Secondary_Male', y='Unemployment_Rate', data=global_education)
      

另外你提到的“Countries and areas”列为object类型,这个不影响当前的lmplot操作,因为你没有用到这个列做分析;后续如果需要按国家分组分析,这个类型也是合理的(字符串类型的分类数据)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 21:27:33