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 9 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 @@ -832,6 +832,7 @@ I/O
- :meth:`to_html` now excludes the ``border`` attribute from ``<table>`` elements when ``border`` keyword is set to ``False``.
- 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 :func:`to_excel` when writing an empty dataframe with row :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
20 changes: 20 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,26 @@ 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):
# Test writing and re-reading an empty MI. GH 19543.

# Initial non-MI frame.
frame1 = DataFrame([[], [], []]).T

# Add a MI.
frame2 = frame1.set_index([0, 1])

# Write out to Excel.
frame2.to_excel(path, "test1")

# Read it back in.
with ExcelFile(path) as reader:
frame3 = pd.read_excel(reader, sheet_name="test1")

# Test that it is the same as the initial frame
# (do not check index and dtype due to empty frame).
tm.assert_frame_equal(frame1, frame3, 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