将 Pandas 数据帧直接转换为稀疏 Numpy 矩阵 [英] Convert Pandas dataframe to Sparse Numpy Matrix directly
本文介绍了将 Pandas 数据帧直接转换为稀疏 Numpy 矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从 Pandas 数据帧创建一个矩阵,如下所示:
I am creating a matrix from a Pandas dataframe as follows:
dense_matrix = np.array(df.as_matrix(columns = None), dtype=bool).astype(np.int)
然后变成一个稀疏矩阵:
And then into a sparse matrix with:
sparse_matrix = scipy.sparse.csr_matrix(dense_matrix)
有没有办法从 df 直接转到稀疏矩阵?
Is there any way to go from a df straight to a sparse matrix?
提前致谢.
推荐答案
df.values
是一个 numpy 数组,以这种方式访问值总是比 np.array
.
df.values
is a numpy array, and accessing values that way is always faster than np.array
.
scipy.sparse.csr_matrix(df.values)
您可能需要先进行转置,例如 df.values.T
.在 DataFrames 中,列是轴 0.
You might need to take the transpose first, like df.values.T
. In DataFrames, the columns are axis 0.
这篇关于将 Pandas 数据帧直接转换为稀疏 Numpy 矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文