应用函数'str'对象没有属性'str'
Apply function 'str' object has no attribute 'str'
因为我真的不明白为什么它在一种格式下有效而在另一种格式下无效。
作品:
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 属性而另一次没有 ....
如果使用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'])
因为我真的不明白为什么它在一种格式下有效而在另一种格式下无效。
作品:
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 属性而另一次没有 ....
如果使用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'])