Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use scikit learn tfidf vectorizer starting from counts data frame

I have a pandas data frame with counts of words for a series of documents. Can I apply sklearn.feature_extraction.text.TfidfVectorizer to it to return a term-document matrix?

import pandas as pd

a = [1,2,3,4]
b = [1,3,4,6]
c = [3,4,6,1]

df = pd.DataFrame([a,b,c])

How can I get tfidf version of counts in df?

like image 895
ADJ Avatar asked Feb 14 '15 00:02

ADJ


1 Answers

like this:

from sklearn.feature_extraction.text import TfidfTransformer
tfidf =TfidfTransformer(norm=u'l2', use_idf=True, smooth_idf=True, sublinear_tf=False)
data =tfidf.fit_transform(df.values)

This returns a sparse matrix of the tfidf values. You can turn them into a dense and put them back into a data frame like this:

pd.DataFrame(data.todense())
like image 103
JAB Avatar answered Sep 24 '22 13:09

JAB