gpt4 book ai didi

python - 如何将 sklearn tfidf 矢量 pandas 输出转换为有意义的格式

转载 作者:行者123 更新时间:2023-12-01 00:37:24 26 4
gpt4 key购买 nike

我已经使用 sklearn 获取我的语料库的 tfidf 分数,但输出不是我想要的格式。

代码:

vect = TfidfVectorizer(ngram_range=(1,3))
tfidf_matrix = vect.fit_transform(df_doc_wholetext['csv_text'])

df = pd.DataFrame(tfidf_matrix.toarray(),columns=vect.get_feature_names())

df['filename'] = df.index

我拥有的:

enter image description here

word1、word2、word3 可以是语料库中的任何单词。例如,我将它们称为 word1 、 word2 、 word3 。

我需要什么:

enter image description here

我尝试对其进行转换,但它会将所有列转换为行。有没有办法实现这一点?

最佳答案

df1 = df.filter(like='word').stack().reset_index()
df1.columns = ['filename','word_name','score']

输出:

   filename word_name  score
0 0 word1 0.01
1 0 word2 0.04
2 0 word3 0.05
3 1 word1 0.02
4 1 word2 0.99
5 1 word3 0.07

常规列标题的更新:

df1 = df.iloc[:,1:].stack().reset_index()

关于python - 如何将 sklearn tfidf 矢量 pandas 输出转换为有意义的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57629697/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com