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

Python DataFrame生成产品分类列报错:AttributeError: 'str'对象无str属性

问题原因与解决方案

错误原因

你循环遍历data_exp['product']时,每一个row都是普通Python字符串对象,而.str.contains()是pandas Series专属的方法,普通字符串没有.str属性,因此触发AttributeError: 'str' object has no attribute 'str'。

解决方案

方法1:修改循环内的字符串判断逻辑

直接用Python原生字符串的子串检查,替换掉pandas的.str方法:

category = []
A = ['a', 'b', 'c', 'd']
B = ['e', 'f', 'j']

for row in data_exp['product']:
    if any(sub in row for sub in A):
        category.append('A')
    elif any(sub in row for sub in B):
        category.append('B')
    else:
        category.append('C')

data_exp['Product category'] = category

方法2:用pandas原生方法(更高效,推荐)

直接对整个列操作,避免循环,适合大数据集:

import numpy as np

# 生成匹配用的正则表达式
pattern_A = '|'.join(['a', 'b', 'c', 'd'])
pattern_B = '|'.join(['e', 'f', 'j'])

# 嵌套np.where实现多条件分类
data_exp['Product category'] = np.where(
    data_exp['product'].str.contains(pattern_A),
    'A',
    np.where(
        data_exp['product'].str.contains(pattern_B),
        'B',
        'C'
    )
)

注意:确认数据集列名是否一致——你描述的列是Product,但代码里用的是product,大小写不匹配会导致额外错误。

内容的提问来源于stack exchange,提问作者I.Kov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:03:13