Skip to content

BUG Avoid IndexError on writing empty (row) MI df to excel (GH19543) #47111

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 15 commits into from
Jun 15, 2022
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,7 @@ I/O
- Bug in :func:`read_sas` returned ``None`` rather than an empty DataFrame for SAS7BDAT files with zero rows (:issue:`18198`)
- Bug in :class:`StataWriter` where value labels were always written with default encoding (:issue:`46750`)
- Bug in :class:`StataWriterUTF8` where some valid characters were removed from variable names (:issue:`47276`)
- Bug in :meth:`to_excel` when writing an empty dataframe with :class:`MultiIndex` (:issue:`19543`)

Period
^^^^^^
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 @@ -634,7 +634,7 @@ def _format_header_regular(self) -> Iterable[ExcelCell]:
if self.index:
coloffset = 1
if isinstance(self.df.index, MultiIndex):
coloffset = len(self.df.index[0])
coloffset = len(self.df.index.names)

colnames = self.columns
if self._has_aliases:
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/io/excel/test_writers.py
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,18 @@ def test_to_excel_multiindex_no_write_index(self, path):
# Test that it is the same as the initial frame.
tm.assert_frame_equal(frame1, frame3)

def test_to_excel_empty_multiindex(self, path):
expected = DataFrame([], columns=[0, 1, 2])

df = DataFrame([], index=MultiIndex.from_tuples([], names=[0, 1]), columns=[2])
df.to_excel(path, "test1")

with ExcelFile(path) as reader:
result = pd.read_excel(reader, sheet_name="test1")
tm.assert_frame_equal(
result, expected, check_index_type=False, check_dtype=False
)

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