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

自定义函数中用str切片报错:AttributeError: 'str' object has no attribute 'str'

问题与解决

问题详情

自定义处理DataFrame的函数时遇到AttributeError: 'str' object has no attribute 'str'错误,函数代码如下:

def region_df(df):
    if (df["Region New"] == "OTHER" and df[['COUNTRY NAME']].notnull().all()):
        return df["REGION NEWER"]
    elif (df["Region New"] == "OTHER" and (df["national Code"].str[:2] == "4A"  or df["national Code"][:1]== "3") ):
        return 'NOT REEQUIRED'
    else :
        return df["Region New"]

单独执行df["national Code"].str[:2] == "4A"能正常得到结果,但放入函数后报错,需求是当national Code以"4A"或"3"开头时返回"NOT REEQUIRED"。

解决方案

错误原因是你大概率用apply(axis=1)调用这个函数,此时传入函数的参数是DataFrame的单行(Series对象),不是整个DataFrame。单行中df["national Code"]是单个字符串,没有.str属性,直接对字符串切片即可,同时补充空值判断避免报错:

修改后的函数:

import pandas as pd

def region_df(row):
    if row["Region New"] == "OTHER" and pd.notnull(row["COUNTRY NAME"]):
        return row["REGION NEWER"]
    elif row["Region New"] == "OTHER":
        national_code = row["national Code"]
        if pd.notnull(national_code):
            if national_code[:2] == "4A" or national_code.startswith("3"):
                return 'NOT REEQUIRED'
        return row["Region New"]
    else:
        return row["Region New"]

核心要点

  • 用apply(axis=1)时,函数接收的是单行数据(Series),列值是单个元素,无需使用.str方法,直接操作字符串
  • 增加pd.notnull(national_code)判断,避免空值切片引发TypeError
  • 把参数名改为row更直观,避免和整个DataFrame混淆

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 13:12:12