Что вы можете сделать, это использовать метод toarray
после transform
, чтобы иметь возможность выполнять умножение матриц на значение счетчика после:
def get_top_n_words(corpus, count, n=None): # add the parameter with the count values
vec = feature_extraction.text.CountVectorizer().fit(corpus)
# here multiply the toarray of transform with the count values
bag_of_words = vec.transform(corpus).toarray()*count.values[:,None]
sum_words = bag_of_words.sum(axis=0)
# accessing the value in sum_words is a bit different but still related to idx
words_freq = [(word, sum_words[idx]) for word, idx in vec.vocabulary_.items()]
words_freq =sorted(words_freq, key = lambda x: x[1], reverse=True)
return words_freq[:n]
common_words = get_top_n_words(df['text'], df['count'], 20)
print (common_words)
[('this', 102),
('is', 102),
('my', 100),
('home', 100),
('where', 10),
('am', 10),
('piece', 2),
('of', 2),
('cake', 2)]