Skip to content

Commit fb4415e

Browse files
committed
Merge pull request #5659 from jmcnamara/bug_to_excel_index_false
BUG: Fix for MultiIndex to_excel() with index=False.
2 parents b3e25a0 + 9c1630d commit fb4415e

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

pandas/core/format.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1375,7 +1375,7 @@ def _format_header_mi(self):
13751375
coloffset = 0
13761376
lnum = 0
13771377

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

13811381
if self.merge_cells:
@@ -1414,10 +1414,11 @@ def _format_header_regular(self):
14141414
has_aliases = isinstance(self.header, (tuple, list, np.ndarray))
14151415
if has_aliases or self.header:
14161416
coloffset = 0
1417+
14171418
if self.index:
14181419
coloffset = 1
1419-
if isinstance(self.df.index, MultiIndex):
1420-
coloffset = len(self.df.index[0])
1420+
if isinstance(self.df.index, MultiIndex):
1421+
coloffset = len(self.df.index[0])
14211422

14221423
colnames = self.columns
14231424
if has_aliases:

pandas/io/tests/test_excel.py

+26-1
Original file line numberDiff line numberDiff line change
@@ -615,7 +615,7 @@ def test_roundtrip_indexlabels(self):
615615
has_index_names=self.merge_cells
616616
).astype(np.int64)
617617
frame.index.names = ['test']
618-
tm.assert_frame_equal(frame,recons.astype(bool))
618+
tm.assert_frame_equal(frame, recons.astype(bool))
619619

620620
with ensure_clean(self.ext) as path:
621621

@@ -715,6 +715,31 @@ def test_to_excel_multiindex_dates(self):
715715
tm.assert_frame_equal(tsframe, recons)
716716
self.assertEquals(recons.index.names, ('time', 'foo'))
717717

718+
def test_to_excel_multiindex_no_write_index(self):
719+
_skip_if_no_xlrd()
720+
721+
# Test writing and re-reading a MI witout the index. GH 5616.
722+
723+
# Initial non-MI frame.
724+
frame1 = pd.DataFrame({'a': [10, 20], 'b': [30, 40], 'c': [50, 60]})
725+
726+
# Add a MI.
727+
frame2 = frame1.copy()
728+
multi_index = pd.MultiIndex.from_tuples([(70, 80), (90, 100)])
729+
frame2.index = multi_index
730+
731+
with ensure_clean(self.ext) as path:
732+
733+
# Write out to Excel without the index.
734+
frame2.to_excel(path, 'test1', index=False)
735+
736+
# Read it back in.
737+
reader = ExcelFile(path)
738+
frame3 = reader.parse('test1')
739+
740+
# Test that it is the same as the initial frame.
741+
tm.assert_frame_equal(frame1, frame3)
742+
718743
def test_to_excel_float_format(self):
719744
_skip_if_no_xlrd()
720745

0 commit comments

Comments
 (0)