【问题标题】:Populate a Pandas SparseDataFrame from a SciPy Sparse Coo Matrix从 SciPy 稀疏 Coo 矩阵填充 Pandas SparseDataFrame
【发布时间】:2016-03-14 21:13:47
【问题描述】:

(这个问题与"populate a Pandas SparseDataFrame from a SciPy Sparse Matrix" 相关。我想从 scipy.sparse 填充一个 SparseDataFrame。coo_matrix(特别是)提到的问题是针对不同的 SciPy 稀疏矩阵( csr)... 就这样吧……)

我注意到 Pandas 现在有 support for Sparse Matrices and Arrays。目前,我这样创建DataFrame()s:

return DataFrame(matrix.toarray(), columns=features, index=observations)

有没有办法用scipy.sparse.coo_matrix()coo_matrix() 创建SparseDataFrame()?转换为密集格式会严重破坏 RAM...!

【问题讨论】:

    标签: python numpy pandas scipy sparse-matrix


    【解决方案1】:

    http://pandas.pydata.org/pandas-docs/stable/sparse.html#interaction-with-scipy-sparse

    实现了一个方便的方法 SparseSeries.from_coo() 从 scipy.sparse.coo_matrix 创建 SparseSeries。

    scipy.sparse 中有一些方法可以将数据形式相互转换。 .tocoo.tocsc 等。因此您可以使用最适合特定操作的形式。

    为了走另一条路,我已经回答了

    Pandas sparse dataFrame to sparse matrix, without generating a dense matrix in memory

    您 2013 年的链接答案逐行迭代 - 使用 toarray 使行密集。我还没看过 pandas from_coo 做了什么。

    关于 pandas sparse 的更新的 SO 问题

    non-NDFFrame object error using pandas.SparseSeries.from_coo() function


    来自https://github.com/pydata/pandas/blob/master/pandas/sparse/scipy_sparse.py

    def _coo_to_sparse_series(A, dense_index=False):
        """ Convert a scipy.sparse.coo_matrix to a SparseSeries.
        Use the defaults given in the SparseSeries constructor. """
        s = Series(A.data, MultiIndex.from_arrays((A.row, A.col)))
        s = s.sort_index()
        s = s.to_sparse()  # TODO: specify kind?
        # ...
        return s
    

    实际上,它采用相同的dataij 用于构建coo 矩阵,创建一个系列,对其进行排序,然后将其变成一个稀疏系列。

    【讨论】:

      猜你喜欢
      • 2013-07-23
      • 2016-10-29
      • 2017-12-04
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 2011-10-02
      • 2019-06-11
      相关资源
      最近更新 更多