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

Pandas对字符串列应用自定义函数报错,如何解决?

解决apply调用自定义字符串列处理函数的AttributeError问题

嘿,这个问题我之前也碰到过!核心原因其实很简单:当你用df.apply(fn_animal, axis=1)的时候,传给fn_animal的x是DataFrame的一行数据(一个Series对象),所以x['animal']是单个的字符串值,而不是整个animal列的Series。这就导致你调用x['animal'].isin(...)直接报错——单个字符串根本没有isin这个方法,这个方法是pandas Series独有的。

要解决这个问题,只需要把函数里的判断逻辑改成针对单个字符串的原生操作就行,不用再用pandas Series的方法了:

def fn_animal(x):
    # 单个字符串用in判断是否在目标列表中,替代Series的isin方法
    if x['animal'] in ['cow', 'hippo']:
        return 1
    # 单个字符串直接用in判断是否包含指定子串,替代str.contains
    elif 'ee' in x['animal']:
        return 0
    else:
        return -1

现在再调用df.apply(fn_animal, axis=1),就能得到你想要的输出了:

0   -1
1    1
2   -1
3    0
4   -1
5    1
dtype: int64

顺便说一句,你之前直接在df['animal']上调用isin和str.contains没问题,是因为df['animal']是一个Series对象,那些方法本来就是为Series设计的。但apply按行传递的时候,每个元素都是单个值,所以得切换成原生字符串的判断方式~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:17:51