python - 将二维列表(tfidf 结果的密集输出)附加到 pandas 数据帧行中,每个索引

标签 python pandas dataframe tf-idf tfidfvectorizer

经过 tfidf 矢量化器后,我得到以下输出。我想将密集输出解析为 pandas dataframe 列,但无法直接将 toarray 或 todense 函数应用于稀疏 tfidf 输出并将其传递给 pandas dataframe 列。所以我收到了 tfidf 结果的密集输出到一个列表中。现在列表的形状为 (6,20),我想将列表的每一行迭代解析为 pandas 数据框列中的行,因为数据框列的长度也是 6。我尝试将列表转换为 pandas 系列并将其传递给数据框,但是不适用于二维列表。

from sklearn.feature_extraction.text import TfidfVectorizer

new_docs = ['Men Tops Tshirts missing ', 'Electronics Computers   Tablets Components Parts Razer',
           'Women Tops   Blouses Blouse Target ', 'Home Home Décor Home Décor Accents missing ', 
           'Women Jewelry Necklaces missing  ', 'Women Other Other missing  ']
vectorizer = TfidfVectorizer(TfidfVectorizer(ngram_range=(1,2),
               min_df=3, max_df=0.9, strip_accents='unicode', use_idf=1,
               smooth_idf=1, sublinear_tf=1 ))
new_term_freq_matrix = vectorizer.fit_transform(new_docs)
print (vectorizer.vocabulary_)
print (new_term_freq_matrix.todense())

example = pd.DataFrame({'test_data_column': new_docs})
lt_1 = []
lt_1 = (vectorizer.fit_transform(new_docs)).toarray()

print(lt_1)

output of lt_1

print(lt_1.shape)
(6, 20)
print(example)
                              test_data_column
0  Men Tops Tshirts missing                              
1  Electronics Computers   Tablets Components Parts Razer
2  Women Tops   Blouses Blouse Target                    
3  Home Home Décor Home Décor Accents missing            
4  Women Jewelry Necklaces missing                       
5  Women Other Other missing          

最佳答案

您可以一次性构建 DataFrame,将 new_docs 作为索引,将 new_term_freq_matrix(TFIDF 值)作为数据传递。

df = pd.DataFrame(new_term_freq_matrix.todense(), index=new_docs)

如果您不想将 new_docs 作为索引,则创建数据帧并稍后插入 new_docs -

df = pd.DataFrame(new_term_freq_matrix.todense())
df.insert(0, 'docs', new_docs)

或者,

df = pd.DataFrame(new_term_freq_matrix.todense(), index=new_docs).reset_index()

前者的性能更高,因为 reset_index 返回整个数据的副本。

另外,如果您正在处理稀疏数据,您可能会对 pd.SparseDataFrame 感兴趣。 API。

关于python - 将二维列表(tfidf 结果的密集输出)附加到 pandas 数据帧行中,每个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48429367/

相关文章:

python - 如何测量python中代码行之间的时间?

python - SQLAlchemy 中查询的单元测试

python - 如何从 pandas.df 的选定行开始 for 循环?

pandas - 在 Taipy 中创建 3D 散点图

python - 使用 python 通过 SQLAlchemy 引擎将 panda 数据框更新到 SQL Server

python - 如何在写入列表时过滤 Pandas 系列

python - 我可以获取 DataFrame 中给定位置的字符串索引和列名吗?

python - 使用现有 TimeSerie 中的索引和另一个 TimeSerie 中的列在 Pandas 中创建 DataFrame

python - 根据分组和条件更新数据框列

python - python 中休假报告逻辑和函数所需的指导