将稀疏矩阵 (csc_matrix) 转换为 Pandas 数据帧 [英] Convert sparse matrix (csc_matrix) to pandas dataframe

查看:63
本文介绍了将稀疏矩阵 (csc_matrix) 转换为 Pandas 数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将此矩阵转换为熊猫数据框.csc_matrix

I want to convert this matrix into a pandas dataframe. csc_matrix

括号中的第一个数字应该是索引第二个数字应该是最后的数字数据.

The first number in the bracket should be the index, the second number being columns and the number in the end being the data.

我想这样做是为了在文本分析中做特征选择,第一个数字代表文档,第二个数字是词的特征,最后一个数字是TFIDF分数.

I want to do this to do feature selection in text analysis, the first number represents the document, the second being the feature of word and the last number being the TFIDF score.

获取数据框帮助我将文本分析问题转化为数据分析.

Getting a dataframe helps me to transform the text analysis problem into data analysis.

推荐答案

from scipy.sparse import csc_matrix

csc = csc_matrix(np.array(
    [[0, 0, 4, 0, 0, 0],
     [1, 0, 0, 0, 2, 0],
     [2, 0, 0, 1, 0, 0],
     [0, 0, 0, 0, 0, 1],
     [4, 0, 3, 2, 0, 0]]))

# Return a Coordinate (coo) representation of the Compresses-Sparse-Column (csc) matrix.
coo = csc.tocoo(copy=False)

# Access `row`, `col` and `data` properties of coo matrix.
>>> pd.DataFrame({'index': coo.row, 'col': coo.col, 'data': coo.data}
                 )[['index', 'col', 'data']].sort_values(['index', 'col']
                 ).reset_index(drop=True)
   index  col  data
0      0    2     4
1      1    0     1
2      1    4     2
3      2    0     2
4      2    3     1
5      3    5     1
6      4    0     4
7      4    2     3
8      4    3     2

这篇关于将稀疏矩阵 (csc_matrix) 转换为 Pandas 数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆