diff --git a/pandas/core/format.py b/pandas/core/format.py index 7135573d48644..f018e0ffdf561 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -1373,7 +1373,7 @@ def _format_header_mi(self): coloffset = 0 lnum = 0 - if isinstance(self.df.index, MultiIndex): + if self.index and isinstance(self.df.index, MultiIndex): coloffset = len(self.df.index[0]) - 1 if self.merge_cells: @@ -1412,10 +1412,11 @@ def _format_header_regular(self): has_aliases = isinstance(self.header, (tuple, list, np.ndarray)) if has_aliases or self.header: coloffset = 0 + if self.index: coloffset = 1 - if isinstance(self.df.index, MultiIndex): - coloffset = len(self.df.index[0]) + if isinstance(self.df.index, MultiIndex): + coloffset = len(self.df.index[0]) colnames = self.columns if has_aliases: diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py index 3446eb07a111e..eeeb914a3754e 100644 --- a/pandas/io/tests/test_excel.py +++ b/pandas/io/tests/test_excel.py @@ -615,7 +615,7 @@ def test_roundtrip_indexlabels(self): has_index_names=self.merge_cells ).astype(np.int64) frame.index.names = ['test'] - tm.assert_frame_equal(frame,recons.astype(bool)) + tm.assert_frame_equal(frame, recons.astype(bool)) with ensure_clean(self.ext) as path: @@ -715,6 +715,31 @@ def test_to_excel_multiindex_dates(self): tm.assert_frame_equal(tsframe, recons) self.assertEquals(recons.index.names, ('time', 'foo')) + def test_to_excel_multiindex_no_write_index(self): + _skip_if_no_xlrd() + + # Test writing and re-reading a MI witout the index. GH 5616. + + # Initial non-MI frame. + frame1 = pd.DataFrame({'a': [10, 20], 'b': [30, 40], 'c': [50, 60]}) + + # Add a MI. + frame2 = frame1.copy() + multi_index = pd.MultiIndex.from_tuples([(70, 80), (90, 100)]) + frame2.index = multi_index + + with ensure_clean(self.ext) as path: + + # Write out to Excel without the index. + frame2.to_excel(path, 'test1', index=False) + + # Read it back in. + reader = ExcelFile(path) + frame3 = reader.parse('test1') + + # Test that it is the same as the initial frame. + tm.assert_frame_equal(frame1, frame3) + def test_to_excel_float_format(self): _skip_if_no_xlrd()