Skip to content

Instantly share code, notes, and snippets.

View mattiasostmar's full-sized avatar

Mattias Östmar mattiasostmar

View GitHub Profile
@seanjtaylor
seanjtaylor / gist:568141f04a16d518be24
Created February 11, 2015 01:46
Reshaping a Pandas dataframe into a sparse matrix
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())