【问题标题】:Most efficient way to str.replace regex=True or similar in pandas?在熊猫中 str.replace regex=True 或类似的最有效方法?
【发布时间】: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


【解决方案1】:

如果我对您的理解正确,您可以使用 pandas replace,连同您的字典和理解来获得您的输出,并提高速度:

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

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

【讨论】:

  • 看起来不错,但有些列不应该应用replace,我不认为将其包含在示例中。我们可以只在某些列上这样做吗?
  • 当然,您可以选择您感兴趣的列。所有数据框的选定列是否相同?
  • 是的,尽管我后来发现绝大多数处理时间是由在连接之前应用替换引起的。将replace 移至pd.concat() 组后,问题基本得到解决。
猜你喜欢
  • 1970-01-01
  • 2016-09-18
  • 2020-07-24
  • 2017-05-08
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 1970-01-01
相关资源
最近更新 更多