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

如何结合if语句与str.contains()创建DataFrame新列并解决属性错误

解决AttributeError: 'str' object has no attribute 'str'问题

错误原因

你用df.apply(f, axis=1)时,传入函数f的row是DataFrame的单行数据(Series对象),但row['ContentTitle']是单个字符串值,不是pandas的Series。而.str.contains()是pandas Series专属的方法,字符串本身没有这个属性,所以触发报错。

解决方案

方案1:修改自定义函数,直接用字符串原生判断

直接用Python字符串的in运算符或find()方法来判断关键词是否存在,替代.str.contains():

def f(row):
    # 判断ContentTitle是否包含目标字符串
    if 'Mama Ntilie' in row['ContentTitle']:
        return 'Mama Ntilie系列'
    # 可添加其他条件
    elif '其他关键词' in row['ContentTitle']:
        return '其他系列'
    else:
        return '未分类'

# 应用函数生成新列
df['标签列'] = df.apply(f, axis=1)

方案2:使用pandas向量化操作(推荐,效率更高)

放弃apply逐行遍历,直接对整个ContentTitle列使用.str.contains()做批量判断,结合np.where或df.loc快速生成标签:

import numpy as np

# 单条件判断
df['标签列'] = np.where(
    df['ContentTitle'].str.contains('Mama Ntilie', na=False),  # na=False处理空值
    'Mama Ntilie系列',
    '未分类'
)

# 多条件嵌套判断
df['标签列'] = np.where(
    df['ContentTitle'].str.contains('Mama Ntilie', na=False),
    'Mama Ntilie系列',
    np.where(
        df['ContentTitle'].str.contains('关键词2', na=False),
        '系列2',
        '未分类'
    )
)

# 或者用df.loc分步赋值(更直观)
df['标签列'] = '未分类'
df.loc[df['ContentTitle'].str.contains('Mama Ntilie', na=False), '标签列'] = 'Mama Ntilie系列'
df.loc[df['ContentTitle'].str.contains('关键词2', na=False), '标签列'] = '系列2'

注意点

  • 使用.str.contains()时,建议加上na=False参数,避免因空值引发报错;
  • 向量化操作比apply逐行遍历效率高得多,数据量越大优势越明显。

内容的提问来源于stack exchange,提问作者Mwai.John

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 02:45:39