python - 获取数据框中大型语料库中选定单词的百分比
问题描述
我有一个关键字列表,如下所示:
keywords = {'dog', 'people', 'bird', 'snake', 'rabbit', 'forest'}
我想获得所有这些单词出现在熊猫数据框中每一行的百分比。列中的每一行都包含很多文本。使用以下代码,我得到了名为perc_words
. 有什么办法可以将其转换为百分比?非常感谢。
import pandas as pd
df['perc_words'] = df['text'].apply(lambda x: sum(i in keywords for i in str(x).split()))
解决方案
您可以使用.str.count()
来计算 的出现次数keywords
,然后除以.str.len()
:
df['perc_words'] = df.text.str.count('|'.join(keywords)) / df.text.str.split().str.len()
要获得每 1000 次的出现次数,您可以乘以perc_words
1000:
df['per_1000'] = df.perc_words * 1000
玩具示例:
df = pd.DataFrame({'text': ['dog apple', 'foo', 'people are people']})
# text
# 0 dog apple
# 1 foo
# 2 people are people
计数keywords
:
df.text.str.count('|'.join(keywords))
# 0 1
# 1 0
# 2 2
# Name: text, dtype: int64
总字数:
df.text.str.split().str.len()
# 0 2
# 1 1
# 2 3
# Name: text, dtype: int64
百分比keywords
:
df['perc_words'] = df.text.str.count(r'|'.join(keywords)) / df.text.str.split().str.len()
df['per_1000'] = df.perc_words * 1000
# text perc_words per_1000
# 0 dog apple 0.500000 500.000000
# 1 foo 0.000000 0.000000
# 2 people are people 0.666667 666.666667
推荐阅读
- sql-server - 如何在 SSIS 中使用 Sharepoint REST API
- javascript - 如何分组并获取具有最大值的元素 - javascript/node.js
- ios - 在没有故事板 Swift 4 的情况下构建 UI 元素
- python - 如何使用 python 代码从二进制文件中读取和提取值?
- python - 关闭emacs中显示大色块的提示
- python - 通过 python 文件到 Robot 框架的命令行参数
- jquery - 在表格主体上方的表格标题中显示选项
- django - 登录期间导致 csrf_token 问题的 Django CustomMiddleware
- java - 如何在微调器上选择项目?
- bash - 如何在不清除屏幕的情况下刷新多行变量输出