Skip to content

Commit

Permalink
add tests and references
Browse files Browse the repository at this point in the history
  • Loading branch information
ZKaoChi committed Nov 8, 2024
1 parent 8cc2a11 commit 71ef0aa
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
7 changes: 4 additions & 3 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,8 +826,8 @@ def _format_hierarchical_rows(self) -> Iterable[ExcelCell]:
allow_fill=levels._can_hold_na,
fill_value=levels._na_value,
)

if isinstance(values, PeriodIndex):
# GH#60099
if isinstance(values[0], Period):
values = values.to_timestamp()

for i, span_val in spans.items():
Expand All @@ -852,7 +853,7 @@ 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()

Expand Down
39 changes: 39 additions & 0 deletions pandas/tests/io/formats/test_to_excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@

from pandas.errors import CSSWarning

from pandas import (
DataFrame,
MultiIndex,
Timestamp,
period_range,
to_datetime,
)
import pandas._testing as tm

from pandas.io.formats.excel import (
Expand Down Expand Up @@ -428,3 +435,35 @@ def test_css_excel_cell_cache(styles, cache_hits, cache_misses):

assert cache_info.hits == cache_hits
assert cache_info.misses == cache_misses


def test_format_hierarchical_rows_with_periodindex():
# GH#60099
period_index = period_range(start="2006-10-06", end="2006-10-07", freq="D")
df = DataFrame({"A": [0, 0]}, index=period_index)
converter = CSSToExcelConverter()
cells: list[CssExcelCell] = list(converter._format_hierarchical_rows(df))
for cell in cells:
assert isinstance(cell.val, Timestamp), "Expected cell value to be a Timestamp"
assert cell.val in to_datetime(
["2006-10-06", "2006-10-07"]
), "Unexpected cell value"


def test_format_hierarchical_rows_with_period():
# GH#60099
period_index = period_range(start="2006-10-06", end="2006-10-07", freq="D")
number_index = ["1", "2"]
df = DataFrame(
{"A": [0, 0]}, index=MultiIndex.from_arrays([period_index, number_index])
)
converter = CSSToExcelConverter()
cells: list[CssExcelCell] = list(converter._format_hierarchical_rows(df))
for cell in cells:
if cell.css_col == 0:
assert isinstance(
cell.val, Timestamp
), "Expected cell value to be a Timestamp"
assert cell.val in to_datetime(
["2006-10-06", "2006-10-07"]
), "Unexpected cell value"

0 comments on commit 71ef0aa

Please sign in to comment.