Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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()

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()

yield CssExcelCell(
row=self.rowcounter + idx,
col=gcolidx,
Expand Down
39 changes: 39 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,39 @@ 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)


def test_format_hierarchical_rows_periodindex_merge_cells():
# GH#60099
df = DataFrame(
{"A": [1, 2]},
index=MultiIndex.from_arrays(
[period_range("2023-01", "2023-02", freq="M"), ["X", "Y"]],
names=["date", "category"],
),
)
formatter = ExcelFormatter(df, merge_cells=True)
formatted_cells = list(formatter._format_hierarchical_rows())

for cell in formatted_cells:
assert not isinstance(
cell.val, Period
), "Period should be converted to Timestamp"


def test_format_hierarchical_rows_periodindex_no_merge_cells():
# GH#60099
df = DataFrame(
{"A": [1, 2]},
index=MultiIndex.from_arrays(
[period_range("2023-01", "2023-02", freq="M"), ["X", "Y"]],
names=["date", "category"],
),
)
formatter = ExcelFormatter(df, merge_cells=False)
formatted_cells = list(formatter._format_hierarchical_rows())

for cell in formatted_cells:
assert not isinstance(
cell.val, Period
), "Period should be converted to Timestamp"
Loading