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

检测DataFrame中Subject字段是否含'OCC'报错:'str'对象无'str'属性

解决'Subject'字符串匹配时的'str' object has no attribute 'str'错误

错误原因

使用iterrows()遍历DataFrame时,row['Subject']返回的是单个Python字符串对象,而.str.contains()是pandas Series(列)的专属方法,不能直接调用在普通字符串上,这就是报错的根源。

解决方案

方案1:修改循环内的判断逻辑(用Python原生字符串方法)

直接用Python原生的in关键字判断字符串是否包含目标子串,同时修正原代码中错误的条件写法:

#messages extracted from pst into data frame
message_df = pd.DataFrame(message_data, columns = ['Subject', 'Body', 'Read Flag'])

#want to check if subject in each of the mail contains OCC word or not
for index, row in message_df.iterrows():
    print("\n For mail # ", index, "Subject is: ", row['Subject'],"\n Body is: ",  row['Body'],"\n Read Flag is: ",  row['Read Flag'], "\n")
    
    # 改用原生字符串判断
    if "OCC" in row['Subject']:
        print("Subject contains OCC: ", row['Subject'])

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

iterrows()逐行遍历效率较低,尤其是数据量大时,推荐直接用pandas的列操作筛选目标行:

#messages extracted from pst into data frame
message_df = pd.DataFrame(message_data, columns = ['Subject', 'Body', 'Read Flag'])

# 筛选Subject包含'OCC'的行,na=False处理空值避免报错
occ_mails = message_df[message_df['Subject'].str.contains("OCC", na=False)]

# 遍历筛选结果打印
for _, row in occ_mails.iterrows():
    print("Subject contains OCC: ", row['Subject'])

# 也可以直接打印筛选后的整个DataFrame
# print(occ_mails)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:01:02