Skip to content

Commit 9abc4e8

Browse files
committed
BUG: Fix .to_excel() for MultiIndex containing a NaN value pandas-dev#13511
1 parent 474fd05 commit 9abc4e8

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

doc/source/whatsnew/v0.19.0.txt

+2
Original file line numberDiff line numberDiff line change
@@ -767,3 +767,5 @@ Bug Fixes
767767
- Bug where ``pd.read_gbq()`` could throw ``ImportError: No module named discovery`` as a result of a naming conflict with another python package called apiclient (:issue:`13454`)
768768
- Bug in ``Index.union`` returns an incorrect result with a named empty index (:issue:`13432`)
769769
- Bugs in ``Index.difference`` and ``DataFrame.join`` raise in Python3 when using mixed-integer indexes (:issue:`13432`, :issue:`12814`)
770+
771+
- Bug in ``.to_excel()`` when DataFrame contains a MultiIndex which contains a label with a NaN value (:issue:`13511`)

pandas/formats/format.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -1839,7 +1839,12 @@ def _format_hierarchical_rows(self):
18391839
for spans, levels, labels in zip(level_lengths,
18401840
self.df.index.levels,
18411841
self.df.index.labels):
1842-
values = levels.take(labels)
1842+
1843+
if levels._can_hold_na:
1844+
values = levels.take(labels, fill_value=True)
1845+
else:
1846+
values = levels.take(labels)
1847+
18431848
for i in spans:
18441849
if spans[i] > 1:
18451850
yield ExcelCell(self.rowcounter + i, gcolidx,

pandas/io/tests/test_excel.py

+14
Original file line numberDiff line numberDiff line change
@@ -1328,6 +1328,20 @@ def test_to_excel_multiindex(self):
13281328
parse_dates=False)
13291329
tm.assert_frame_equal(frame, df)
13301330

1331+
# GH13511
1332+
def test_to_excel_multiindex_nan_label(self):
1333+
_skip_if_no_xlrd()
1334+
1335+
frame = self.frame
1336+
frame.A = np.arange(len(frame))
1337+
frame.iloc[0, 0] = None
1338+
frame.set_index(['A', 'B'], inplace=True)
1339+
1340+
with ensure_clean(self.ext) as path:
1341+
frame.to_excel(path, merge_cells=self.merge_cells)
1342+
df = read_excel(path, index_col=[0, 1])
1343+
tm.assert_frame_equal(frame, df)
1344+
13311345
# Test for Issue 11328. If column indices are integers, make
13321346
# sure they are handled correctly for either setting of
13331347
# merge_cells

0 commit comments

Comments
 (0)