Skip to content

PERF: sparse to_csv #49066

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

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
20 changes: 20 additions & 0 deletions asv_bench/benchmarks/io/csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,26 @@ def time_head_of_multiindex(self):
self.df_custom_index_then_head.to_csv(self.fname)


class ToCSVSparse(BaseIO):

fname = "__test__.csv"

def setup(self):
from scipy import sparse as sc

vals = np.random.randint(0, 10, size=(10000, 1000))
keep = vals > 3
vals[keep] = 0
sparse_mtx = sc.coo_matrix(vals)
self.data = DataFrame.sparse.from_spmatrix(sparse_mtx)

def time_sparse_to_csv(self):
self.data.to_csv("sparse_pd.csv")

def time_sparse_to_dense_to_csv(self):
self.data.sparse.to_dense().to_csv("sparse_pd.csv")


class StringIORewind:
def data(self, stringio_object):
stringio_object.seek(0)
Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ Performance improvements
- Performance improvements to :func:`read_sas` (:issue:`47403`, :issue:`47405`, :issue:`47656`, :issue:`48502`)
- Memory improvement in :meth:`RangeIndex.sort_values` (:issue:`48801`)
- Performance improvement in :class:`DataFrameGroupBy` and :class:`SeriesGroupBy` when ``by`` is a categorical type and ``sort=False`` (:issue:`48976`)
- Performance improvement for saving to CSV with :class:`CSVFormatter` when data frame is sparse (:issue:`41023`)

.. ---------------------------------------------------------------------------
.. _whatsnew_200.bug_fixes:
Expand Down
5 changes: 4 additions & 1 deletion pandas/io/formats/csvs.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@ def __init__(
) -> None:
self.fmt = formatter

self.obj = self.fmt.frame
if hasattr(self.fmt.frame, "sparse"):
self.obj = self.fmt.frame.sparse.to_dense()
else:
self.obj = self.fmt.frame

self.filepath_or_buffer = path_or_buf
self.encoding = encoding
Expand Down