【问题标题】:Sklearn - group by category and get top n words from each category of dataframe?Sklearn - 按类别分组并从每个数据框类别中获取前 n 个单词?
【发布时间】: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


    【解决方案1】:

    不确定这是否是您正在寻找的,但您可以尝试:

    result.groupby('type')['post'].agg(pd.Series.mode) 来自https://stackoverflow.com/a/54304691/5323399

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-20
      • 2021-10-04
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      • 2013-01-01
      • 1970-01-01
      相关资源
      最近更新 更多