Skip to content

PERF: optimize DataFrame.sparse.from_spmatrix performance #32825

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Mar 22, 2020
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion asv_bench/benchmarks/sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ def time_sparse_array(self, dense_proportion, fill_value, dtype):
class SparseDataFrameConstructor:
def setup(self):
N = 1000
self.arr = np.arange(N)
self.sparse = scipy.sparse.rand(N, N, 0.005)

def time_from_scipy(self):
Expand Down
4 changes: 4 additions & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,10 @@ Performance improvements
- The internal index method :meth:`~Index._shallow_copy` now copies cached attributes over to the new index,
avoiding creating these again on the new index. This can speed up many operations that depend on creating copies of
existing indexes (:issue:`28584`, :issue:`32640`, :issue:`32669`)
- Significant performance improvement when creating a :class:`DataFrame` with
sparse values from ``scipy.sparse`` matrices using the
:meth:`DataFrame.sparse.from_spmatrix` constructor (:issue:`32821`,
:issue:`32825`, :issue:`32826`, :issue:`32856`, :issue:`32858`).

.. ---------------------------------------------------------------------------

Expand Down
7 changes: 5 additions & 2 deletions pandas/_libs/sparse.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,21 @@ cdef class IntIndex(SparseIndex):
length : integer
indices : array-like
Contains integers corresponding to the indices.
check_integrity : bool, default=True
Check integrity of the input.
"""

cdef readonly:
Py_ssize_t length, npoints
ndarray indices

def __init__(self, Py_ssize_t length, indices):
def __init__(self, Py_ssize_t length, indices, bint check_integrity=True):
self.length = length
self.indices = np.ascontiguousarray(indices, dtype=np.int32)
self.npoints = len(self.indices)

self.check_integrity()
if check_integrity:
self.check_integrity()

def __reduce__(self):
args = (self.length, self.indices)
Expand Down
25 changes: 20 additions & 5 deletions pandas/core/arrays/sparse/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,14 +228,29 @@ def from_spmatrix(cls, data, index=None, columns=None):
2 0.0 0.0 1.0
"""
from pandas import DataFrame
from pandas._libs.sparse import IntIndex

data = data.tocsc()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could be tocsc(copy=False) for newer scipy versions, but the gain in performance is minimal anyway with respect to the total runtime.

index, columns = cls._prep_index(data, index, columns)
Copy link
Member

@jorisvandenbossche jorisvandenbossche Mar 22, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the problem is that this _pre_index doesn't actually return Index objects when columns or index is not None (and passing actual Index objects is required when doing verify_integrity=False)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I see. Thanks for confirming that passing duplicate columns names in an Index object is expected to work in _from_arrays. Will look into it. Thanks Joris!

Copy link
Member

@jorisvandenbossche jorisvandenbossche Mar 22, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That seems to be it, as doing pd.DataFrame.sparse.from_spmatrix(mat, columns=pd.Index(['a', 'a'])) instead of pd.DataFrame.sparse.from_spmatrix(mat, columns=['a', 'a']) works.

You can add in here a ensure_index call on both index and columns. (from pandas.core.indexes.api import ensure_index)

sparrays = [SparseArray.from_spmatrix(data[:, i]) for i in range(data.shape[1])]
data = dict(enumerate(sparrays))
result = DataFrame(data, index=index)
result.columns = columns
return result
n_rows, n_columns = data.shape
# We need to make sure indices are sorted, as we create
# IntIndex with no input validation (i.e. check_integrity=False ).
# Indices may already be sorted in scipy in which case this adds
# a small overhead.
data.sort_indices()
Copy link
Contributor Author

@rth rth Mar 19, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be already done in tocsc, but that's a scipy implementation detail, and it doesn't really cost much. We need to make sure indices are sorted, since we create IntIndex with check_integrity=False that used to check for this.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add a comment about that inline?

indices = data.indices
indptr = data.indptr
array_data = data.data
dtype = SparseDtype(array_data.dtype, 0)
arrays = []
for i in range(n_columns):
sl = slice(indptr[i], indptr[i + 1])
idx = IntIndex(n_rows, indices[sl], check_integrity=False)
arr = SparseArray._simple_new(array_data[sl], idx, dtype)
arrays.append(arr)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, also tried with a generator here to avoid pre-allocating all the arrays, but it doesn't really matter. Most of the remaining run time is in DataFrame._from_arrays.

return DataFrame._from_arrays(
arrays, columns=columns, index=index, verify_integrity=False
)

def to_dense(self):
"""
Expand Down