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

在if/elif/else自定义函数中创建DataFrame列,为何无法使用str.contains?

报错原因

.str是Pandas Series(列级对象)专属的矢量化字符串处理属性,仅支持作用于整列数据。当你使用axis=1逐行调用apply时,row['summary']取到的是该行对应位置的原生字符串类型,自然没有.str属性,也就无法调用.str.contains方法。

调整方案

仅需要对自定义函数内的字符串匹配逻辑做少量修改即可,不需要改动「自定义函数+apply」的整体实现框架,完全可以满足你的多分支逻辑需求,不存在无法实现的情况。

修改后的代码如下:

import re

def func(row):
    if row['condition'] == True:
        # 用原生正则匹配替代Series.str.contains,逻辑完全对齐
        if re.search(r'hi|there', row['summary'], flags=re.IGNORECASE):
            return 'hi_there'
        else:
            return 'Other'
    else:
        if re.search(r'goodbye|you', row['summary'], flags=re.IGNORECASE):
            return 'goodbye_you'
        else:
            return 'Other'

# 可省略多余的lambda封装,直接传入函数即可
df['newcolumn'] = df.apply(func, axis=1)

如果你不需要正则匹配,仅做简单子串判断,也可以用更轻量化的写法:

def func(row):
    summary_lower = row['summary'].lower()
    if row['condition'] == True:
        if 'hi' in summary_lower or 'there' in summary_lower:
            return 'hi_there'
        else:
            return 'Other'
    else:
        if 'goodbye' in summary_lower or 'you' in summary_lower:
            return 'goodbye_you'
        else:
            return 'Other'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:57:02