我不完全确定您要做什么,但您似乎只是想弄清楚哪一列代表哪个单词。为此,有方便的get_feature_names 参数。
让我们看一下docs中提供的示例语料库:
corpus = [
'This is the first document.',
'This document is the second document.',
'And this is the third one.',
'Is this the first document?' ]
# Put into a dataframe
data = pd.DataFrame(corpus,columns=['description'])
# Take a look:
>>> data
description
0 This is the first document.
1 This document is the second document.
2 And this is the third one.
3 Is this the first document?
# Initialize CountVectorizer (you can put in your arguments, but for the sake of example, I'm keeping it simple):
vec = CountVectorizer()
# Fit it as you had before:
features = vec.fit_transform(data.loc[:,"description"]).todense()
>>> features
matrix([[0, 1, 1, 1, 0, 0, 1, 0, 1],
[0, 2, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 0, 1, 1, 0, 1, 1, 1],
[0, 1, 1, 1, 0, 0, 1, 0, 1]], dtype=int64)
要查看哪一列代表哪个单词,请使用get_feature_names:
>>> vec.get_feature_names()
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
所以您的第一列是and,第二列是document,依此类推。为了便于阅读,您可以将其粘贴在数据框中:
>>> pd.DataFrame(features, columns = vec.get_feature_names())
and document first is one second the third this
0 0 1 1 1 0 0 1 0 1
1 0 2 0 1 0 1 1 0 1
2 1 0 0 1 1 0 1 1 1
3 0 1 1 1 0 0 1 0 1