【发布时间】:2020-08-26 10:39:31
【问题描述】:
我有一个这样布局的 pd 数据框并命名为 result:
target type post
1 intj "hello world shdjd"
2 entp "hello world fddf"
16 estj "hello world dsd"
4 esfp "hello world sfs"
1 intj "hello world ddfd"
每个帖子都是独一无二的,目标只是为 16 种类型中的每一种分配编号 1-16。条目数以万计,但 16 种类型重复。
我正在关注Pandas groupby category, rating, get top value from each category?,试图为 16 个类别中的每一个类别下的所有帖子提取前 n 个最常用的词。
根据 SO 帖子,我需要 1) 将每种类型的所有帖子分组并 2) 为 16 个帖子中的每一个运行 TfidfVectorizer。使这变得困难的是数据框有多大。
到目前为止,我尝试使用以下方法进行分组:
result = result.reset_index()
print(result.loc[result.groupby('type').post.agg('idxmax')])
但这给出了 ValueError,因为我认为 agg 只能与数字一起使用。而且我需要将所有字符串附加到一个中。
在最上面的单词部分,我有这个例子:
tfidf = TfidfVectorizer(stop_words='english')
corpus = [
'I would like to check this document',
'How about one more document',
'Aim is to capture the key words from the corpus',
'frequency of words in a document is called term frequency'
]
X = tfidf.fit_transform(corpus)
feature_names = np.array(tfidf.get_feature_names())
new_doc = ['can key words words words in this new document be identified?',
'idf is the inverse document frequency frequency frequency caculcated for each of the words']
responses = tfidf.transform(new_doc)
def get_top_tf_idf_words(response, top_n=2):
sorted_nzs = np.argsort(response.data)[:-(top_n+1):-1]
return feature_names[response.indices[sorted_nzs]]
我猜在分组之后,我会运行一个 for 循环,为 16 个非常长的字符串中的每一个获取最重要的单词?
我怎样才能正确地做到这一点?
【问题讨论】:
标签: python pandas machine-learning scikit-learn countvectorizer