为了优化,我想知道是否可以在一列中使用来自另一列的相应行的内容进行更快的字符串替换,而不使用apply。
这是我的数据框:
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 ms
使用替换(感谢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μs/循环
总的来说,看起来像拉链是这里的最佳选择。感谢所有的投入!
答案 0 :(得分:1)
试试这个:
df['file'] = df['file'].astype(str)
df['root'] = df['root'].astype(str)
df['file'].replace(df['root'],'', regex=True)
输出:
0 system32/calc.exe
Name: file, dtype: object
答案 1 :(得分:1)
使用与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
使用zip:
%%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