pandas.DataFrame.sparse.from_spmatrix

pandas 3.1.1 · DataFrame · method

Create a sparse pandas object from a SciPy sparse matrix.

Call syntax

DataFrame.sparse.from_spmatrix(data, index=None, columns=None)

Inspect the call

Run this code to inspect the callable and its parameters. Its data, backend, or environment is needed to execute the operation itself.

Parameters

ParameterRequirementAccepted values and behavior
data Required
Positional or keyword
scipy.sparse.spmatrix

Provide the input data read, transformed, or stored by this call.

index Optional
Positional or keyword
Default None
Index

Supply row labels or control how existing row labels are used.

columns Optional
Positional or keyword
Default None
Index

Supply column labels or control how columns are handled.

Returns

DataFrame

Example for a local Python session

import pandas as pd
import scipy.sparse
frame = pd.DataFrame({"units": [2., 5., 7.], "price": [4., 3., 2.]})
frame = frame.astype(pd.SparseDtype("float64", 0))
print(frame.sparse.from_spmatrix(scipy.sparse.coo_matrix([[0, 2], [5, 0]])))