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

使用pandas apply时遇TypeError: string indices must be integers错误求助

问题解决:TypeError: string indices must be integers

错误原因

你调用df['列名'].apply(q1)时,apply是作用在Series的单个元素上,传入q1的参数x是列中的单个值(比如字符串'Extremely likely'或'3'),而非DataFrame的行对象。所以函数里的x['How likely are you to recommend us to a colleague?']相当于对字符串使用字符串索引,违反了Python字符串只能用整数索引的规则,导致报错。

解决方案

方案1:修改函数适配Series元素处理

调整q1函数,直接处理单个元素值:

def q1(x):
    if x == 'Extremely likely':
        return 10
    elif x == 'Not at all likely':
        return 0
    else:
        # 若原列的1-9是字符串类型,转成整数;若已是数字则直接返回
        return int(x) if isinstance(x, str) else x

调用方式不变:

df['How likely are you to recommend us to a colleague?'] = df['How likely are you to recommend us to a colleague?'].apply(q1)

方案2:用replace更简洁实现

不需要自定义函数,直接用字典映射替换值,再统一转类型:

mapping = {
    'Extremely likely': 10,
    'Not at all likely': 0
}
col_name = 'How likely are you to recommend us to a colleague?'
df[col_name] = df[col_name].replace(mapping).astype(int)

方案3:用numpy.where嵌套判断

适合逻辑简单的场景,代码更直观:

import numpy as np

col_name = 'How likely are you to recommend us to a colleague?'
df[col_name] = np.where(
    df[col_name] == 'Extremely likely',
    10,
    np.where(
        df[col_name] == 'Not at all likely',
        0,
        df[col_name].astype(int)
    )
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:20:58