Skip to main content
 首页 » 编程设计

python之系列字符串替换为另一个系列的内容(不使用应用)

2024年10月01日29lexus

为了优化,我想知道是否可以在一列中使用另一列中相应行的内容进行更快的字符串替换,而不使用应用。

这是我的数据框:

data_dict = {'root': [r'c:/windows/'], 'file': [r'c:/windows/system32/calc.exe']} 
df = pd.DataFrame.from_dict(data_dict) 
 
""" 
Result: 
                           file         root 
0  c:/windows/system32/calc.exe  c:/windows/ 
""" 

使用以下申请,我可以获得我想要的:

df['trunc'] = df.apply(lambda x: x['file'].replace(x['path'], ''), axis=1) 
 
""" 
Result: 
                           file         root              trunc 
0  c:/windows/system32/calc.exe  c:/windows/  system32/calc.exe  
""" 

但是,为了更有效地使用代码,我想知道是否有更好的方法。我已经尝试了下面的代码,但它似乎没有按我预期的方式工作。

df['trunc'] = df['file'].replace(df['root'], '') 
 
""" 
Result (note that the root was NOT properly replaced with a black string in the 'trunc' column): 
 
                           file         root                         trunc 
0  c:/windows/system32/calc.exe  c:/windows/  c:/windows/system32/calc.exe 
""" 

有没有更有效的替代品?谢谢!

编辑 - 使用以下几个示例的时间

# Expand out the data set to 1000 entries 
data_dict = {'root': [r'c:/windows/']*1000, 'file': [r'c:/windows/system32/calc.exe']*1000} 
df0 = pd.DataFrame.from_dict(data_dict) 

使用应用

%%timeit -n 100 
df0['trunk0'] = df0.apply(lambda x: x['file'].replace(x['root'], ''), axis=1) 

100 次循环,最好的 3 次:每次循环 13.9 毫秒

使用替换(感谢 Gayatri)

%%timeit -n 100 
df0['trunk1'] = df0['file'].replace(df0['root'], '', regex=True) 

100 次循环,最好的 3 次:每次循环 365 毫秒

使用 Zip(感谢 0p3n5ourcE)

%%timeit -n 100 
df0['trunk2'] = [file_val.replace(root_val, '') for file_val, root_val in zip(df0.file, df0.root)] 

100 次循环,最好的 3 次:每次循环 600 微秒

总的来说,看起来 zip 是最好的选择。感谢所有的输入!

请您参考如下方法:

使用与 link 中类似的方法

df['trunc'] = [file_val.replace(root_val, '') for file_val, root_val in zip(df.file, df.root)] 

输出:

                          file         root              trunc 
0  c:/windows/system32/calc.exe  c:/windows/  system32/calc.exe 

使用 timeit 检查:

%%timeit 
df['trunc'] = df.apply(lambda x: x['file'].replace(x['root'], ''), axis=1) 

结果:

1000 loops, best of 3: 469 µs per loop 

使用压缩包:

%%timeit 
df['trunc'] = [file_val.replace(root_val, '') for file_val, root_val in zip(df.file, df.root)] 

结果:

1000 loops, best of 3: 322 µs per loop