Convert Pandas dataframe to Sparse Numpy Matrix directly Convert Pandas dataframe to Sparse Numpy Matrix directly pandas pandas

Convert Pandas dataframe to Sparse Numpy Matrix directly


df.values is a numpy array, and accessing values that way is always faster than np.array.

scipy.sparse.csr_matrix(df.values)

You might need to take the transpose first, like df.values.T. In DataFrames, the columns are axis 0.