【发布时间】:2021-11-08 08:57:03
【问题描述】:
数十个字符串需要在数千个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 或类似的? Use CstringIO like this answer suggests 不知何故? Some kind of vectorization?
结合dfs后应用str.replace可能效率更高,但pd.concat() blows out of available memory。
编辑:下面的粗略可重现示例。请注意,当通过减少每个 df 的行数来保持单元格总数不变时,经过的时间如何随着 dfs 的数量线性增加(使用shape[0] 和range(0,1000)):
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)
【问题讨论】:
-
两个/三个小 dfs、字典和预期输出的可重现示例将很有用/有帮助
标签: python regex pandas replace