【发布时间】:2018-02-24 13:48:56
【问题描述】:
我有 10M 文本(适合 RAM)和一个 Python 字典:
"old substring":"new substring"
字典的大小约为 15k 个子字符串。
我正在寻找用 dict 替换每个文本的最快方法(在每个文本中查找每个“旧子字符串”并将其替换为“新子字符串”)。
源文本位于 pandas 数据框中。 目前我已经尝试了这些方法:
1) 在循环中用 reduce 和 str 替换替换(~120 行/秒)
replaced = []
for row in df.itertuples():
replaced.append(reduce(lambda x, y: x.replace(y, mapping[y]), mapping, row[1]))
2) 在循环中使用简单的替换功能(“映射”是 15k 字典)(~160 行/秒):
def string_replace(text):
for key in mapping:
text = text.replace(key, mapping[key])
return text
replaced = []
for row in tqdm(df.itertuples()):
replaced.append(string_replace(row[1]))
.iterrows() 的工作速度也比 .itertuples() 慢 20%
3) 在 Series 上使用 apply(也是 ~160 行/秒):
replaced = df['text'].apply(string_replace)
以这样的速度处理整个数据集需要几个小时。
任何人都有这种大规模子字符串替换的经验?有没有可能加快速度?它可能很棘手或丑陋,但必须尽可能快,而不需要使用 pandas。
谢谢。
更新: 玩具数据来检验这个想法:
df = pd.DataFrame({ "old":
["first text to replace",
"second text to replace"]
})
mapping = {"first text": "FT",
"replace": "rep",
"second": '2nd'}
预期结果:
old replaced
0 first text to replace FT to rep
1 second text to replace 2nd text to rep
【问题讨论】:
-
谢谢 Wiktor,我现在看到了 regexp=True 的想法,但它比头帖中的简单方法慢得多。
标签: string pandas numpy replace substring