Pandas 将每个文档转换为基于TF-IDF的向量

Pandas 将每个文档转换为基于TF-IDF的向量,pandas,dataframe,tensorflow,plot,tf-idf,Pandas,Dataframe,Tensorflow,Plot,Tf Idf,我在下面编写了计算TF-IDF分数的代码 docs=['ali is a good boy', 'a good boy is not bad', 'ali is not bad but bad is good'] cv=CountVectorizer() # this steps generates word counts for the words in your docs word_count_vector=cv.fit_transform(docs) print

我在下面编写了计算TF-IDF分数的代码

docs=['ali is a good boy',
      'a good boy is not bad',
      'ali is not bad but bad is good']

cv=CountVectorizer()

# this steps generates word counts for the words in your docs
word_count_vector=cv.fit_transform(docs)
print(word_count_vector)
tfidf_transformer=TfidfTransformer(smooth_idf=True,use_idf=True)
tfidf_transformer.fit(word_count_vector)

# print idf values
df_idf = pd.DataFrame(tfidf_transformer.idf_, index=cv.get_feature_names(),columns=["idf_weights"])
# sort ascending
df_idf.sort_values(by=['idf_weights'])

# count matrix
count_vector=cv.transform(docs)
# tf-idf scores
tf_idf_vector=tfidf_transformer.transform(count_vector)
feature_names = cv.get_feature_names()
print(feature_names)
#get tfidf vector for first document
first_document_vector=tf_idf_vector[0]
#for first_document_vector in tf_idf_vector:
#print the scores
df=(pd.DataFrame(first_document_vector.T.todense().transpose(),columns=feature_names))
df.to_csv('file1.csv') 
1-最终我能够得到第一个文档的向量。但是我不能得到所有文档的向量。我尝试循环并附加到数据帧,但没有成功。 2-如何将文档索引保存在csv文件中?

我必须在电影镜头数据集中的电影情节上运行它。这就是为什么保存documnet的索引对我来说很重要。

要获取所有文档的向量:

#get tfidf vector for all documents
all_document_vector = tf_idf_vector
df= pd.DataFrame(all_document_vector.T.todense().transpose(),columns=feature_names)
要导出带有索引的csv文件,请执行以下操作:

df.to_csv('file1.csv',index=True, index_label = 'Index') 

谢谢@manojk,我尝试了你建议的代码,但是我得到了内存错误。我能做些什么来避免它发生内存错误可能有多种原因,请尝试将df=pd.DataFrame(all_document\u vector.T.todense().transpose(),columns=feature\u names)更改为df=pd.DataFrame(all_document\u vector.T.toarray().transpose(),columns=feature\u names)如果这有帮助,或者您可以使用内存不足的。toarray()也有同样的问题。我不能使用哈希向量器。由于它有文档页面上列出的限制,请尝试使用
max\u功能限制字数。您使用的是32位系统吗?这里给出了一些解决方案