Created
February 11, 2015 01:46
-
-
Save seanjtaylor/568141f04a16d518be24 to your computer and use it in GitHub Desktop.
Reshaping a Pandas dataframe into a sparse matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import scipy.sparse as sps | |
df = pd.DataFrame({'tag1': ['sean', 'udi', 'bogdan'], 'tag2': ['sean', 'udi', 'udi'], 'freq': [1,2,3]}) | |
# tag1 -> rows, tag2 -> columns | |
df.set_index(['tag1', 'tag2'], inplace=True) | |
mat = sps.coo_matrix((df.freq, (df.index.labels[0], df.index.labels[1]))) | |
print(mat.todense()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment