python - 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 的方法有什么建议和想法吗?
解决方案
不要遍历巨大的 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,'')
推荐阅读
- terraform - 将现有作业 Rundeck 转换为 .tfstate
- amazon-web-services - AWS EC2 t3.micro 实例对于 Spring Boot 服务足够稳定
- winforms - 从 Windows 窗体应用程序向 Unity 发送消息
- postgresql - 如何优化 Postgres 中多个表(5000 万行)的联接和合并的运行时
- mongodb - 在 Azure Web App for Containers 中将 Mongodb 卷挂载到 Azure 文件
- jekyll - 无法在“nil”上使用 concat
- vb.net - 如何在 vb.net 或 c# 中将 DataTable[] 转换为 DataSet
- plugins - Tuleap 中的验证码
- javascript - 如何从函数 JavaScript 中返回结果值
- ruby - 循环多个数组