Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.