将稀疏矩阵转换为pandas数据框架


import numpy as np
from scipy.sparse import csr_matrix
csr = csr_matrix(np.array(
[[0, 0, 4],
[1, 0, 0],
[2, 0, 0],]))
# Return a Coordinate (coo) representation of the csr matrix.
coo = csr.tocoo(copy=False)
# Access `row`, `col` and `data` properties of coo matrix.
df = pd.DataFrame({'index': coo.row, 'col': coo.col, 'data': coo.data})[['index', 'col', 'data']]
>>> df.head()
index  col  data
0    0     2     4
1    1     0     1
2    2     0     2

我尝试将一个scipy csr_matrix矩阵转换为一个数据框架,其中的列表示矩阵的索引、列和数据。

唯一的问题是,我上面尝试的并没有为值为0的列生成行。下面是我想要的输出:

>>> df.head()
index  col  data
0    0     0     0
1    0     1     0
2    0     2     4
3    1     0     1
4    1     1     0
5    1     2     0
6    2     0     2
7    2     1     0
8    2     2     0

您将看到上面的代码片段取自这个线程中的这个答案。

我的请求/问题是否有一种方法可以将矩阵转换为df,并且还包括矩阵中值为0的元素?

  • 将稀疏矩阵转换为密集矩阵填充0
  • 将密集矩阵转换为pandas数据框架
  • melt数据帧从'宽'到'长'格式
df = your_sparse_matrix_data.todense()
(pd.DataFrame(df)
.melt()
.reset_index()
.rename(columns = {'index':'row','variable':'column'}))

一种方法是创建一个fillingDataFrame并将其(使用combine_first)与您已经拥有的DataFrame组合:

df = pd.DataFrame({'index': coo.row, 'col': coo.col, 'data': coo.data}).set_index(["index", "col"])
n_rows, n_cols = coo.shape
rows, cols = map(np.ndarray.flatten, np.mgrid[:n_rows, :n_cols])
filling = pd.DataFrame({"index": rows, "col": cols, "data": np.repeat(0, n_rows * n_cols)}) 
.set_index(["index", "col"])
res = df.combine_first(filling).reset_index()
print(res)

index  col  data
0      0    0   0.0
1      0    1   0.0
2      0    2   4.0
3      1    0   1.0
4      1    1   0.0
5      1    2   0.0
6      2    0   2.0
7      2    1   0.0
8      2    2   0.0

最新更新