Issue
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)
Is there any way to go from a df straight to a sparse matrix?
Thanks in advance.
Solution
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.
Answered By - Dan Allan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.