Skip to content
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ MultiIndex

I/O
^^^
- Bug in :class:`io.formats.excel.ExcelFormatter` when writing empty :class:`DataFrame` with :class:`MultiIndex` on both axes (:issue:`57696`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe ExcelFormatter is private; can you change to to :meth:`DataFrame.to_excel`

-
-

Expand Down
2 changes: 1 addition & 1 deletion pandas/io/formats/excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,7 @@ def _format_header_mi(self) -> Iterable[ExcelCell]:
lnum = 0

if self.index and isinstance(self.df.index, MultiIndex):
coloffset = len(self.df.index[0]) - 1
coloffset = self.df.index.nlevels - 1

if self.merge_cells:
# Format multi-index as a merged cells.
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/io/excel/test_writers.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,6 +936,17 @@ def test_to_excel_empty_multiindex(self, tmp_excel):
result, expected, check_index_type=False, check_dtype=False
)

def test_to_excel_empty_multiindex_both_axes(self, tmp_excel):
# GH 57696
df = DataFrame(
[],
index=MultiIndex.from_tuples([], names=[0, 1]),
columns=MultiIndex.from_tuples([("A", "B")]),
)
df.to_excel(tmp_excel)
result = pd.read_excel(tmp_excel, header=None)
assert result.iloc[:2, -1].to_list() == ["A", "B"]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you test the entire result? I think if you change the read line to

result = pd.read_excel("tmp.xlsx", header=[0, 1], index_col=[0, 1])

Then you should just be able to do

tm.assert_frame_equal(result, df)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks, that looks better and works exactly like you said.


def test_to_excel_float_format(self, tmp_excel):
df = DataFrame(
[[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
Expand Down