【发布时间】:2021-12-14 00:35:47
【问题描述】:
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
你会看到上面的代码 sn-p 取自this answer in this thread。
我的请求/问题:有没有办法将矩阵转换为 df 并包含值为 0 的矩阵元素?
【问题讨论】:
标签: python pandas dataframe matrix scipy