1 Upvote

Create Bag of Words DataFrame Using Count Vectorizer

Transforms a dataframe text column into a new "bag of words" dataframe using the sklearn count vectorizer. First the count vectorizer is initialised before being used to transform the "text" column from the dataframe "df" to create the initial bag of words. This output from the count vectorizer is then converted to a dataframe by converting the output to an array and then passing this Into the parameters of the dataframe along with feature names from the count vectorizer which gives us the column names.

from sklearn.feature_extraction.text import CountVectorizer
count_vectorizer = CountVectorizer()
bag_of_words = count_vectorizer.fit_transform(df['text'])
bag_of_words = pd.DataFrame(bag_of_words.toarray(),
				columns = count_vectorizer.get_feature_names())

By detro - Last Updated Nov. 1, 2021, 4:44 p.m.

Search Snippets by Tag: