python - 当单词数小于 N 时,删除 pandas 数据框中的字符串行
问题描述
我正在为 NLP 分类任务预处理数据集,我想删除少于 3 个单词的句子,我尝试删除少于 3 个字母的单词的代码:
import re
text = "The quick brown fox jumps over the lazy dog."
# remove words between 1 and 3
shortword = re.compile(r'\W*\b\w{1,3}\b')
print(shortword.sub('', text))
如何在python中做到这一点?
解决方案
使用 Pandas 数据框:
import pandas
text = {"header":["The quick fox","The quick fox brown jumps hight","The quick"]}
df = pandas.DataFrame(text)
df = df[df['header'].str.split().str.len().gt(2)]
print(df)
上面的代码片段过滤了 'header' 列长度大于 2 个单词的数据帧。
有关 pandas 数据框的更多信息,请参阅https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html
推荐阅读
- ajax - 会话过期后的 Ajax 调用未重定向到登录页面 - 春季启动
- reactjs - React forwardRef:你可以向下传递多深的forwardRef?
- javascript - 标头发送后如何重定向node.js
- javascript - 为什么使用成功承诺调用 catch?
- docker - Dockerfile EXPOSE 命令是否支持 ${bash//search/replace}?
- ruby-on-rails - Rails 5.2 Active Storage:如何确定并确保没有直接上传的浮动 blob
- android - 如何从本地存储中的文件而不是 res/raw 中的硬编码文件中进行选择?
- java - 在 localhost 上运行时访问 jBoss Business Central Maven 存储库的 URL 是什么
- swift - 没有像右视图一样向 textField 添加标签
- apache-spark - 如何通过 ["x","y"] dropDuplicates 而不改组已经由 "x" 分区的 spark 数据帧