Skip to content

Commit 4c2840e

Browse files
mpuelsjorisvandenbossche
authored andcommitted
BUG: Fix .to_excel() for MultiIndex containing a NaN value pandas-dev#13511 (pandas-dev#13551)
1 parent 2166ac1 commit 4c2840e

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

doc/source/whatsnew/v0.19.0.txt

+2
Original file line numberDiff line numberDiff line change
@@ -772,3 +772,5 @@ Bug Fixes
772772
- 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`)
773773
- Bug in ``Index.union`` returns an incorrect result with a named empty index (:issue:`13432`)
774774
- Bugs in ``Index.difference`` and ``DataFrame.join`` raise in Python3 when using mixed-integer indexes (:issue:`13432`, :issue:`12814`)
775+
776+
- Bug in ``.to_excel()`` when DataFrame contains a MultiIndex which contains a label with a NaN value (:issue:`13511`)

pandas/formats/format.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -1839,7 +1839,11 @@ 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+
values = levels.take(labels,
1844+
allow_fill=levels._can_hold_na,
1845+
fill_value=True)
1846+
18431847
for i in spans:
18441848
if spans[i] > 1:
18451849
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 = pd.DataFrame({'A': [None, 2, 3],
1336+
'B': [10, 20, 30],
1337+
'C': np.random.sample(3)})
1338+
frame = frame.set_index(['A', 'B'])
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)