首页 > 解决方案 > Pandas:从大型数据集中的数据框字符串中的特定列表中删除所有单词

问题描述

所以我有三个熊猫数据框(训练,测试)。总体而言,它大约是 700k 行。我想从城市列表中删除所有城市 - common_cities。但笔记本单元格中的 tqdm 表明,从 33000 个城市列表中替换所有城市大约需要 24 小时。

dataframe example (train_original)

ID 名称_1 名称_2
0 遮阳帘装饰巴黎公司 indl de cuautitlan sa 简历
1 EIH有限公司 东莞卫士 纽约塑料制品有限公司
2 杰士有限公司 (香港) 墨西哥城 阿拉伯造船厂首尔和修理厂马德里 c

common_cities list example

common_cities = ['moscow', 'madrid', 'san francisco', 'mexico city']

what is supposed to be output

ID 名称_1 名称_2
0 太阳百叶窗装饰公司 独立的简历
1 EIH有限公司 卫士 塑胶制品有限公司
2 杰士有限公司 (香港) 阿拉伯造船和修理厂 c

在这种情况下,我的解决方案在小的过滤词列表上效果很好,但是当它很大时,性能很低。

%%time

for city in tqdm(common_cities):
    train_original.replace(re.compile(fr'\b({city})\b'), '', inplace=True)
    train_augmented.replace(re.compile(fr'\b({city})\b'), '', inplace=True)
    test.replace(re.compile(fr'\b({city})\b'), '', inplace=True)

PS:我认为在拆分字符串和替换城市名称时使用列表理解并不是很好,因为城市名称可能> 2 个单词。

在这种情况下快速替换 Pandas Dataframes 的方法有什么建议和想法吗?

标签: pythonpandasperformancedataframebigdata

解决方案


不要遍历巨大的 dfs 以获取到达通道,请记住pandas 替换接受字典,所有替换都可以一次性完成。

因此,我们可以从创建字典开始,然后使用它replace

replacements = {x:'' for x in common_cities}
train_original = train_original.replace(replacements)
train_augmented = train_augmented.replace(replacements)
test = test.replace(replacements)

编辑:阅读文档可能会更容易,因为它还接受要替换的值列表:

train_original = train_original.replace(common_cities,'')
train_augmented = train_augmented.replace(common_cities,'')
test = test.replace(common_cities,'')

推荐阅读