If A is csr_matrix
, 您可以使用.toarray() http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.csr_matrix.toarray.html#scipy.sparse.csr_matrix.toarray(还有.todense()
产生一个numpy
matrix
,这也适用于DataFrame
构造函数):
df = pd.DataFrame(A.toarray())
然后你可以使用它pd.concat()
.
A = csr_matrix([[1, 0, 2], [0, 3, 0]])
(0, 0) 1
(0, 2) 2
(1, 1) 3
<class 'scipy.sparse.csr.csr_matrix'>
pd.DataFrame(A.todense())
0 1 2
0 1 0 2
1 0 3 0
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 3 columns):
0 2 non-null int64
1 2 non-null int64
2 2 non-null int64
在0.20版本中,pandas
介绍稀疏数据结构 https://pandas.pydata.org/pandas-docs/stable/sparse.html#sparse-data-structures, 包括SparseDataFrame https://pandas.pydata.org/pandas-docs/stable/sparse.html#sparsedataframe.
在熊猫1.0中,SparseDataFrame
was removed https://pandas.pydata.org/pandas-docs/stable/user_guide/sparse.html#migrating:
在旧版本的 pandas 中,SparseSeries
and SparseDataFrame
类是处理稀疏数据的首选方式。随着扩展数组的出现,不再需要这些子类。通过使用具有稀疏值的常规 Series 或 DataFrame 可以更好地满足其目的。
The 移民 https://pandas.pydata.org/pandas-docs/stable/user_guide/sparse.html#migrating指南展示了如何使用这些新的数据结构。
例如,要创建一个DataFrame
从稀疏矩阵:
from scipy.sparse import csr_matrix
A = csr_matrix([[1, 0, 2], [0, 3, 0]])
df = pd.DataFrame.sparse.from_spmatrix(A, columns=['A', 'B', 'C'])
df
A B C
0 1 0 2
1 0 3 0
df.dtypes
A Sparse[float64, 0]
B Sparse[float64, 0]
C Sparse[float64, 0]
dtype: object
或者,您可以将稀疏矩阵传递给sklearn
以避免转换回时内存不足pandas
。只需通过传递一个参数将其他数据转换为稀疏格式numpy
array
to the scipy.sparse.csr_matrix
构造函数和使用scipy.sparse.hstack
合并(参见docs https://docs.scipy.org/doc/scipy/reference/sparse.html).