【问题标题】:Convert sparse matrix to pandas dataframe将稀疏矩阵转换为熊猫数据框
【发布时间】: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


    【解决方案1】:

    一种方法是创建一个filling DataFrame 并将其(使用combine_first)与您已有的数据框结合起来:

    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
    

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 2015-01-16
      • 2023-04-10
      • 2021-11-25
      • 2017-07-02
      • 2020-04-07
      • 1970-01-01
      • 2016-08-26
      • 2020-12-09
      相关资源
      最近更新 更多