Skip to content

Instantly share code, notes, and snippets.

@Keiku
Created April 28, 2017 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Keiku/d1a377b8e6d04d84da77cb870c581219 to your computer and use it in GitHub Desktop.
Save Keiku/d1a377b8e6d04d84da77cb870c581219 to your computer and use it in GitHub Desktop.
Stack the sparse matrices.
import numpy as np
import scipy as sp
import pandas as pd
df1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
df2 = pd.DataFrame({"C": [5, 6]})
X1 = sp.sparse.csr_matrix(df1.values)
X1_dense = X1.todense()
# Out[28]:
# matrix([[1, 3],
# [2, 4]], dtype=int64)
X2 = sp.sparse.csr_matrix(df2.values)
X2_dense = X2.todense()
# Out[29]:
# matrix([[5],
# [6]], dtype=int64)
X3 = np.hstack(X1, X2)
X3_dense = np.hstack([X1_dense, X2_dense])
# Out[32]:
# matrix([[1, 3, 5],
# [2, 4, 6]], dtype=int64)
X3 = sp.sparse.hstack([X1, X2])
X3.todense()
# Out[35]:
# matrix([[1, 3, 5],
# [2, 4, 6]], dtype=int64)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment