最有效的方法str.replace regex=True或类似的熊猫?



需要在数千dfs的多个列中替换数十个字符串:

for df in dfs:
for col in columns:
for key, value in replacement_strs.items():
df[col] = df[col].str.replace(key, value, regex=True)

上面的迭代需要几毫秒,但是加起来需要几个小时,所以我们需要更高效的方法。

我们是否可以更有效地应用re_sub或类似的方法?像这个答案暗示的那样使用CstringIO ?某种矢量化?

合并dfs后使用str.replace可能会更有效,但pd.concat()会耗尽可用内存。

编辑:下面的原始可复制示例。请注意,当通过减少每个df的行数来保持单元总数不变时(使用shape[0]range(0,1000)),运行时间如何随着dfs的数量线性增加:

import pandas as pd, numpy as np, string, random
from timeit import default_timer as timer
np.random.seed(123)
dfs = []
shape = [500, 10]
df = pd.DataFrame(np.arange(shape[0] * shape[1]).reshape(shape[0],shape[1])).applymap(lambda x: np.random.choice(list(string.ascii_letters.upper())))
for n in range(0,1000):
dfs.append(df)
start = timer()
for df in dfs:
for col in [col for col in range(0,shape[1])]:
for key, value in {'A$': 'W','B': 'X','C[a-z]': 'Y','D': 'Z',}.items():
df[col] = df[col].str.replace(key, value, regex=True)
end = timer()
print(end - start)

如果我理解正确的话,您可以使用pandas替换、字典和理解来获得输出,从而提高速度:

mapping = {'A$': 'W','B': 'X','C[a-z]': 'Y','D': 'Z',}
[entry.replace(mapping, regex = False) for entry in dfs]

在我的电脑上,你的函数运行了17秒,而上面的列表理解运行了1.2秒。可能会有改进(生成器、多处理)。在进一步优化之前(如果真的需要的话),使用replace是一个好的开始。

最新更新