如何在Pandas数据框中找到一列的ngram频率?

14

以下是我拥有的输入pandas数据框。

enter image description here

我想找到unigrams和bigrams的频率。下面显示了我期望结果的示例enter image description here

如何使用nltk或scikit learn进行操作?

我编写了以下代码,它以字符串作为输入。如何将其扩展到系列/数据框?

from nltk.collocations import *
desc='john is a guy person you him guy person you him'
tokens = nltk.word_tokenize(desc)
bigram_measures = nltk.collocations.BigramAssocMeasures()
finder = BigramCollocationFinder.from_words(tokens)
finder.ngram_fd.viewitems()
1个回答

32
如果你的数据是这样的
import pandas as pd
df = pd.DataFrame([
    'must watch. Good acting',
    'average movie. Bad acting',
    'good movie. Good acting',
    'pathetic. Avoid',
    'avoid'], columns=['description'])

您可以使用 sklearn 包中的 CountVectorizer 来实现:
from sklearn.feature_extraction.text import CountVectorizer
word_vectorizer = CountVectorizer(ngram_range=(1,2), analyzer='word')
sparse_matrix = word_vectorizer.fit_transform(df['description'])
frequencies = sum(sparse_matrix).toarray()[0]
pd.DataFrame(frequencies, index=word_vectorizer.get_feature_names(), columns=['frequency'])

这将为您提供:

                frequency
good            3
pathetic        1
average movie   1
movie bad       2
watch           1
good movie      1
watch good      3
good acting     2
must            1
movie good      2
pathetic avoid  1
bad acting      1
average         1
must watch      1
acting          1
bad             1
movie           1
avoid           1

编辑

fit会“训练”您的向量化程序:它将拆分您的语料库中的单词,并创建一个词汇表。然后,transform可以获取新文档并基于向量化程序词汇表创建频率向量。

在这里,您的训练集是您的输出集,因此您可以同时进行两者(fit_transform)。因为您有5个文档,所以它将创建5个向量作为矩阵。您想要全局向量,因此您必须进行sum操作。

编辑2

对于大型数据框,您可以通过使用以下方法加快频率计算:

frequencies = sum(sparse_matrix).data

或者

frequencies = sparse_matrix.sum(axis=0).T

+1 你能解释一下fit_transform() / fit() / transform()之间的区别吗?你是怎么发现sum(sparse_matrix).toarray()[0]可以得到频率的?我在scikit learn文档中没有找到太多相关信息。 - GeorgeOfTheRF
@ML_Pro 我在答案中添加了一个解释。 - Till
标记为答案。非常有帮助的解释。 - GeorgeOfTheRF
1
@Till - sum(sparse_matrix).data 给出了错误的频率。 - Alaa M.
总和太慢了。您可以执行 frequencies = sparse_matrix.sum(axis=0).T - Aaron Soellinger
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接