sdf = df.sparse.from_spmatrix()
已更新,用于将DataFrame转换为稀疏DataFrame的方法是什么?
sdf = df.sparse.from_spmatrix()
已更新,用于将DataFrame转换为稀疏DataFrame的方法是什么?
以下是pandas 1.0.0+中更新的稀疏转换。
使用适当的SparseDtype()
(例如,int
),结合DataFrame.astype()
将DataFrame转换为稀疏矩阵。
>>> df = pd.DataFrame({'A': [1, 0, 0, 0, 1, 0]})
>>> df.dtypes
# A int64
# dtype: object
>>> sdf = df.astype(pd.SparseDtype(int, fill_value=0))
>>> sdf.dtypes
# A Sparse[int64, 0]
# dtype: object
或者使用字符串别名以缩短长度:
>>> sdf = df.astype('Sparse[int64, 0]')
使用 DataFrame.sparse.to_dense()
函数:
>>> from scipy import sparse
>>> sdf = pd.DataFrame.sparse.from_spmatrix(sparse.eye(3), columns=list('ABC'))
>>> sdf.dtypes
# A Sparse[float64, 0]
# B Sparse[float64, 0]
# C Sparse[float64, 0]
# dtype: object
>>> df = sdf.sparse.to_dense()
>>> df.dtypes
# A float64
# B float64
# C float64
# dtype: object
>>> from scipy import sparse
>>> sdf = pd.DataFrame.sparse.from_spmatrix(sparse.eye(3), columns=list('ABC'))
>>> sdf.dtypes
# A Sparse[float64, 0]
# B Sparse[float64, 0]
# C Sparse[float64, 0]
# dtype: object
>>> df = sdf.sparse.to_coo()
# <3x3 sparse matrix of type '<class 'numpy.float64'>'
# with 3 stored elements in COOrdinate format>
# (0, 0) 1.0
# (1, 1) 1.0
# (2, 2) 1.0
scipy
似乎不会出现错误,那么需要在这里使用 scipy
吗? - user2165scipy.sparse
仅在此处需要用于示例数据sparse.eye(3)
。 - tdyscipy.sparse.csr_matrix(df.values)