From b576b350e81ba150fd65cc29fd3d42f14efb04aa Mon Sep 17 00:00:00 2001 From: Andy Hayden Date: Mon, 8 Sep 2014 21:56:51 -0700 Subject: [PATCH] ENH to_latex mi index will use & sep for levels --- pandas/core/format.py | 21 ++++++++++++++++----- pandas/tests/test_format.py | 6 +++--- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/pandas/core/format.py b/pandas/core/format.py index 339cd9344f089..3f03db6dcf93f 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -513,12 +513,23 @@ def get_col_type(dtype): else: strcols = self._to_str_columns() + if self.index and isinstance(self.frame.index, MultiIndex): + fmt = self._get_formatter('__index__') + clevels = self.frame.columns.nlevels + strcols.pop(0) + name = any(self.frame.columns.names) + for i, lev in enumerate(self.frame.index.levels): + lev2 = lev.format(name=name) + width = len(lev2[0]) + lev3 = [' ' * width] * clevels + lev2 + strcols.insert(i, lev3) + if column_format is None: dtypes = self.frame.dtypes.values + column_format = ''.join(map(get_col_type, dtypes)) if self.index: - column_format = 'l%s' % ''.join(map(get_col_type, dtypes)) - else: - column_format = '%s' % ''.join(map(get_col_type, dtypes)) + index_format = 'l' * self.frame.index.nlevels + column_format = index_format + column_format elif not isinstance(column_format, compat.string_types): # pragma: no cover raise AssertionError('column_format must be str or unicode, not %s' @@ -645,8 +656,8 @@ def has_index_names(self): def has_column_names(self): return _has_names(self.frame.columns) - def _get_formatted_index(self,frame): - # Note: this is only used by to_string(), not by to_html(). + def _get_formatted_index(self, frame): + # Note: this is only used by to_string() and to_latex(), not by to_html(). index = frame.index columns = frame.columns diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index aa19865342fab..64b0fd6ebf199 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -2098,11 +2098,11 @@ def test_to_latex_multiindex(self): self.assertEqual(result, expected) result = df.T.to_latex() - expected = r"""\begin{tabular}{ll} + expected = r"""\begin{tabular}{lll} \toprule -{} & 0 \\ + & & 0 \\ \midrule -x y & a \\ +x & y & a \\ \bottomrule \end{tabular} """