python - 从 Pandas 系列中删除单词在文本中出现的次数少于 2 次
问题描述
我正在尝试删除 Pandas 系列中每个标量值中出现的所有单词。最好的方法是什么?这是我失败的尝试:
from collections import Counter
df = pd.DataFrame({'text':["The quick brown fox", "jumped over the lazy dog","jumped over the lazy dog"]})
d=''.join(df['text'][:])
m=d.split()
q=Counter(m)
print (q)
df['text'].str.split().map(lambda el: " ".join(Counter(el for el in q.elements() if q[el] >= 2)))
out put :
Counter({'over': 2, 'the': 2, 'lazy': 2, 'The': 1, 'quick': 1, 'brown': 1, 'foxjumped': 1, 'dogjumped': 1, 'dog': 1})
0 over the lazy
1 over the lazy
2 over the lazy
Name: text, dtype: object
解决方案
from collections import Counter
df = pd.DataFrame({'text':["The quick brown fox", "jumped over the lazy dog","jumped over the lazy dog"]})
c = Counter(df.text.str.split().explode())
print( df.text.apply(lambda x: ' '.join(w for w in x.split() if c[w] >= 2).strip()) )
印刷:
0
1 jumped over the lazy dog
2 jumped over the lazy dog
Name: text, dtype: object
推荐阅读
- c# - Visual Code 仍然运行旧项目并且不运行新项目
- javascript - 无法删除事件监听器
- c# - 让多节车厢的火车在贝塞尔路径上行驶
- algorithm - 算法可以是一条指令吗?
- html - 阻止网络刮刀在 R 中显示 404 错误
- android - 如何通过 Xamarin 表单中的依赖服务更新视图模型?
- azure-keyvault - 尝试将自定义角色“秘密读者”分配给 Azure Key Vault 的对象 ID 时出错
- javascript - javascript 如何在不影响键的情况下将对象推入数组?
- php - APT 说“软件包没有安装候选者”虽然它显示在 apt 列表中
- javascript - 我们是否在使用 await 的异步函数上使用 await?