【问题标题】:Apply function 'str' object has no attribute 'str'应用函数“str”对象没有属性“str”
【发布时间】:2022-01-20 08:16:06
【问题描述】:

因为我真的不明白为什么它在一种格式中有效而在另一种格式中无效。

作品:

df['team'] = df['team'].str.extract(r'(\w+)+')

不起作用:

def clear_teams(gr):
    return gr.str.extract(r'(\w+)+')
        
df['team'] = df['team'].apply(clear_teams)

我收到一个错误:

AttributeError: 'str' object has no attribute 'str'

为什么它不起作用,有人可以向我解释一下吗?请:) 它是如何一次具有 str 属性而另一次没有 ....

【问题讨论】:

    标签: python pandas dataframe apply


    【解决方案1】:

    如果使用Series.apply,那么函数gr 是标量,函数按Series 的元素循环。所以不能像str.extract那样使用Series函数,而是通过标量处理的解决方案:

    def clear_teams(gr):
        try:
            return re.search(r'(\w+)+', text).group(1)
        except:
            return np.nan   
    
    df['team'] = df['team'].apply(clear_teams)
    

    如果使用Series.pipe,那么gr 就是Series,都可以正常工作:

    def clear_teams(gr):
        return gr.str.extract(r'(\w+)+')
    
    df['team'] = df['team'].pipe(clear_teams)
    

    或者:

    df['team'] = clear_teams(df['team'])
    

    【讨论】:

    • 但是为什么它不适用于 apply ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2016-09-20
    • 2019-03-25
    • 2017-05-13
    • 2014-04-28
    • 2015-05-15
    相关资源
    最近更新 更多