Sklearn - 按类别分组并从每个类别的数据框中获取前 n 个词?

Sklearn - group by category and get top n words from each category of dataframe?

我有一个这样布局的 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"

每个post都是唯一的,target只是为16种类型中的每一种分配编号1-16。有数万个条目,但16种类型重复。

我正在关注 ,试图为 16 个类别中的每个类别下的所有 post 拉出前 n 个最常用的词。

根据 SO post,我需要 1) 将每种类型的所有 post 分组,以及 2) 运行 TfidfVectorizer 为 16 种类型中的每一种分组。困难的是数据框有多大。

到目前为止,我尝试使用以下方式进行分组:

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 个非常长的字符串中的每一个获取顶部词?

我怎样才能正确地做到这一点?

不确定这是否是您要查找的内容,但您可以尝试:

result.groupby('type')['post'].agg(pd.Series.mode) 来自

如果您想查看多个最高值,您可以尝试使用针对该问题列出的 value_counts() 的 lambda 函数,只在函数末尾添加 nlargest()