Skip to content
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

BUG: Convert output type in Excel for MultiIndex with period levels #60182

Merged
merged 17 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from 13 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
8 changes: 8 additions & 0 deletions pandas/io/formats/excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
DataFrame,
Index,
MultiIndex,
Period,
PeriodIndex,
)
import pandas.core.common as com
Expand Down Expand Up @@ -825,6 +826,9 @@ def _format_hierarchical_rows(self) -> Iterable[ExcelCell]:
allow_fill=levels._can_hold_na,
fill_value=levels._na_value,
)
# GH#60099
if isinstance(values[0], Period):
values = values.to_timestamp()
ZKaoChi marked this conversation as resolved.
Show resolved Hide resolved

for i, span_val in spans.items():
mergestart, mergeend = None, None
Expand All @@ -849,6 +853,10 @@ def _format_hierarchical_rows(self) -> Iterable[ExcelCell]:
# Format hierarchical rows with non-merged values.
for indexcolvals in zip(*self.df.index):
for idx, indexcolval in enumerate(indexcolvals):
# GH#60099
if isinstance(indexcolval, Period):
indexcolval = indexcolval.to_timestamp()
ZKaoChi marked this conversation as resolved.
Show resolved Hide resolved

yield CssExcelCell(
row=self.rowcounter + idx,
col=gcolidx,
Expand Down
25 changes: 25 additions & 0 deletions pandas/tests/io/excel/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@

from pandas import (
DataFrame,
MultiIndex,
Period,
period_range,
read_excel,
)
import pandas._testing as tm
Expand Down Expand Up @@ -333,3 +336,25 @@ def test_styler_to_s3(s3_public_bucket, s3so):
f"s3://{mock_bucket_name}/{target_file}", index_col=0, storage_options=s3so
)
tm.assert_frame_equal(result, df)


@pytest.mark.parametrize("merge_cells", [True, False, "columns"])
def test_format_hierarchical_rows_periodindex(merge_cells):
# GH#60099
df = DataFrame(
{"A": [1, 2]},
index=MultiIndex.from_arrays(
[
period_range(start="2006-10-06", end="2006-10-07", freq="D"),
["X", "Y"],
],
names=["date", "category"],
),
)
formatter = ExcelFormatter(df, merge_cells=merge_cells)
formatted_cells = list(formatter._format_hierarchical_rows())
ZKaoChi marked this conversation as resolved.
Show resolved Hide resolved

for cell in formatted_cells:
assert not isinstance(
ZKaoChi marked this conversation as resolved.
Show resolved Hide resolved
cell.val, Period
), "Period should be converted to Timestamp"
40 changes: 40 additions & 0 deletions pandas/tests/io/excel/test_writers.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
MultiIndex,
date_range,
option_context,
period_range,
)
import pandas._testing as tm

Expand Down Expand Up @@ -337,6 +338,45 @@ def test_multiindex_interval_datetimes(self, tmp_excel):
)
tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize("merge_cells", [True, False, "columns"])
def test_excel_round_trip_with_periodindex(self, tmp_excel, merge_cells):
# GH#60099
df = DataFrame(
{"A": [1, 2]},
index=MultiIndex.from_arrays(
[
period_range(start="2006-10-06", end="2006-10-07", freq="D"),
["X", "Y"],
],
names=["date", "category"],
),
)
df.to_excel(tmp_excel, merge_cells=merge_cells)
result = pd.read_excel(tmp_excel, index_col=[0, 1])
expected = DataFrame(
{"A": [1, 2]},
MultiIndex.from_arrays(
[
[
pd.to_datetime("2006-10-06 00:00:00"),
pd.to_datetime("2006-10-07 00:00:00"),
],
["X", "Y"],
],
names=["date", "category"],
),
)
if tmp_excel.endswith(".ods"):
expected.index = expected.index.set_levels(
expected.index.levels[0].astype("datetime64[s]"), level=0
)
else:
expected.index = expected.index.set_levels(
expected.index.levels[0].astype("datetime64[us]"), level=0
)

tm.assert_frame_equal(result, expected)


@pytest.mark.parametrize(
"engine,ext",
Expand Down