与str.replace
内置函数相比,DataFrame包装器的性能下降了5倍。有谁知道是什么原因造成的?
df = pd.DataFrame({'word':['bird']*100000})
%timeit df.word.str.replace('bird','theword')
%timeit df.word.map(lambda x: x.replace('bird','theword'))
1 loops, best of 3: 266 ms per loop
10 loops, best of 3: 55.4 ms per loop
原因是str.replace
将能够处理NaN,而使用lambda进行的自定义替换将在此方面发生错误:
In [17]: df.iloc[0,0] = np.nan
In [18]: df.word.str.replace('bird','theword').head()
Out[18]:
0 NaN
1 theword
2 theword
3 theword
4 theword
Name: word, dtype: object
In [19]: df.word.map(lambda x: x.replace('bird','theword'))
AttributeError: 'float' object has no attribute 'replace'
在内部,str.replace
还使用lambda x: x.replace(pat, repl, n)
(如果不使用case或flags关键字,则它将使用regex)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句