Skip to content

PERF: Improve performance in to_csv with date format for index #44908

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 3 commits into from
Dec 16, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 12 additions & 0 deletions asv_bench/benchmarks/io/csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,18 @@ def time_frame_date_formatting(self):
self.data.to_csv(self.fname, date_format="%Y%m%d")


class ToCSVDatetimeIndex(BaseIO):

fname = "__test__.csv"

def setup(self):
rng = date_range("2000", periods=100_000, freq="S")
self.data = DataFrame({"a": 1}, index=rng)

def time_frame_date_formatting_index(self):
self.data.to_csv(self.fname, date_format="%Y-%m-%d %H:%M:%S")


class ToCSVDatetimeBig(BaseIO):

fname = "__test__.csv"
Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,7 @@ Performance improvements
- Performance improvement in :meth:`Series.to_frame` (:issue:`43558`)
- Performance improvement in :meth:`Series.mad` (:issue:`43010`)
- Performance improvement in :func:`merge` (:issue:`43332`)
- Performance improvement in :func:`to_csv` when index column is a datetime and is formatted (:issue:`39413`)
- Performance improvement in :func:`read_csv` when ``index_col`` was set with a numeric column (:issue:`44158`)
- Performance improvement in :func:`concat` (:issue:`43354`)
-
Expand Down
4 changes: 2 additions & 2 deletions pandas/io/formats/csvs.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ def __init__(
self.line_terminator = line_terminator or os.linesep
self.date_format = date_format
self.cols = self._initialize_columns(cols)
self.data_index = self.get_data_index()
self.chunksize = self._initialize_chunksize(chunksize)

@property
Expand Down Expand Up @@ -175,8 +176,7 @@ def _number_format(self) -> dict[str, Any]:
"decimal": self.decimal,
}

@property
def data_index(self) -> Index:
def get_data_index(self) -> Index:
data_index = self.obj.index
if (
isinstance(data_index, (ABCDatetimeIndex, ABCPeriodIndex))
Expand Down