首页 > 解决方案 > 获取数据框中大型语料库中选定单词的百分比

问题描述

我有一个关键字列表,如下所示:

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()))

标签: pythonpython-3.xpandasnlp

解决方案


您可以使用.str.count()来计算 的出现次数keywords,然后除以.str.len()

df['perc_words'] = df.text.str.count('|'.join(keywords)) / df.text.str.split().str.len()

要获得每 1000 次的出现次数,您可以乘以perc_words1000:

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

推荐阅读