簡體   English   中英

Sklearn - 按類別分組並從 dataframe 的每個類別中獲取前 n 個單詞?

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

我有一個 pd dataframe 像這樣布局並命名為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"

每個帖子都是唯一的,target 只為 16 種類型中的每一種分配編號 1-16。 條目數以萬計,但 16 種類型重復。

我關注Pandas 分組類別,評級,從每個類別中獲得最高價值? 試圖為 16 個類別中的每一個類別下的所有帖子提取前 n 個最常用的詞。

根據 SO 帖子,我需要 1)對每種類型的所有帖子進行分組,以及 2)為 16 個中的每一個運行 TfidfVectorizer。使這變得困難的是 dataframe 有多大。

到目前為止,我嘗試使用以下方法進行分組:

result = result.reset_index()
print(result.loc[result.groupby('type').post.agg('idxmax')])

但這給出了 ValueError ,因為我認為agg只能與數字一起使用。 而我需要將 append 所有的字符串合二為一。

在最上面的詞部分,我有這個例子:

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)來自https://stackoverflow.com/a/54304691/5323399

如果您想查看多個最高值,您可以嘗試使用 lambda function 和value_counts() ,就像為該問題列出的一樣,只在 ZC1C4252078E68384F1AB417A 的末尾添加nlargest()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM