diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt index 736554672a089..e4a3183983fa9 100755 --- a/doc/source/whatsnew/v0.17.1.txt +++ b/doc/source/whatsnew/v0.17.1.txt @@ -42,3 +42,4 @@ Performance Improvements Bug Fixes ~~~~~~~~~ +Bug in ``.to_latex()`` output broken when the index has a name (:issue: `10660`) diff --git a/pandas/core/format.py b/pandas/core/format.py index 5f12abb543513..1ad6f250187ee 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -636,11 +636,13 @@ def get_col_type(dtype): if self.index and isinstance(self.frame.index, MultiIndex): clevels = self.frame.columns.nlevels strcols.pop(0) - name = any(self.frame.columns.names) + name = any(self.frame.index.names) for i, lev in enumerate(self.frame.index.levels): - lev2 = lev.format(name=name) + lev2 = lev.format() blank = ' ' * len(lev2[0]) lev3 = [blank] * clevels + if name: + lev3.append(lev.name) for level_idx, group in itertools.groupby( self.frame.index.labels[i]): count = len(list(group)) @@ -667,6 +669,8 @@ def write(buf, frame, column_format, strcols, longtable=False): buf.write('\\toprule\n') nlevels = frame.columns.nlevels + if any(frame.index.names): + nlevels += 1 for i, row in enumerate(zip(*strcols)): if i == nlevels: buf.write('\\midrule\n') # End of header diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index b5220c8cb2706..b96a6d09983b5 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -2645,6 +2645,50 @@ def test_to_latex_multiindex(self): c3 & 0 & 0 & 1 & 2 & 3 \\ \bottomrule \end{tabular} +""" + self.assertEqual(result, expected) + + # GH 10660 + df = pd.DataFrame({'a':[0,0,1,1], 'b':list('abab'), 'c':[1,2,3,4]}) + result = df.set_index(['a', 'b']).to_latex() + expected = r"""\begin{tabular}{llr} +\toprule + & & c \\ +a & b & \\ +\midrule +0 & a & 1 \\ + & b & 2 \\ +1 & a & 3 \\ + & b & 4 \\ +\bottomrule +\end{tabular} +""" + self.assertEqual(result, expected) + + result = df.groupby('a').describe().to_latex() + expected = r"""\begin{tabular}{llr} +\toprule + & & c \\ +a & {} & \\ +\midrule +0 & count & 2.000000 \\ + & mean & 1.500000 \\ + & std & 0.707107 \\ + & min & 1.000000 \\ + & 25\% & 1.250000 \\ + & 50\% & 1.500000 \\ + & 75\% & 1.750000 \\ + & max & 2.000000 \\ +1 & count & 2.000000 \\ + & mean & 3.500000 \\ + & std & 0.707107 \\ + & min & 3.000000 \\ + & 25\% & 3.250000 \\ + & 50\% & 3.500000 \\ + & 75\% & 3.750000 \\ + & max & 4.000000 \\ +\bottomrule +\end{tabular} """ self.assertEqual(result, expected)