如何将sklearn tfidf矢量熊猫输出转换为有意义的格式

时间:2019-08-23 16:04:12

标签: python pandas scikit-learn tf-idf tfidfvectorizer

我已经使用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

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

1 个答案:

答案 0 :(得分:2)

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()