【发布时间】:2016-10-02 06:36:42
【问题描述】:
我想从下面的文档中计算 tf-idf。我正在使用 python 和 pandas。
import pandas as pd
df = pd.DataFrame({'docId': [1,2,3],
'sent': ['This is the first sentence','This is the second sentence', 'This is the third sentence']})
首先,我认为我需要为每一行获取 word_count。于是我写了一个简单的函数:
def word_count(sent):
word2cnt = dict()
for word in sent.split():
if word in word2cnt: word2cnt[word] += 1
else: word2cnt[word] = 1
return word2cnt
然后,我将它应用到每一行。
df['word_count'] = df['sent'].apply(word_count)
但现在我迷路了。如果我使用 Graphlab,我知道有一种简单的方法可以计算 tf-idf,但我想坚持使用开源选项。 Sklearn 和 gensim 都显得势不可挡。获取 tf-idf 最简单的解决方案是什么?
【问题讨论】:
标签: python pandas scikit-learn tf-idf gensim