Skip to content

Commit b576b35

Browse files
committed
ENH to_latex mi index will use & sep for levels
1 parent 5bbe99e commit b576b35

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

pandas/core/format.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -513,12 +513,23 @@ def get_col_type(dtype):
513513
else:
514514
strcols = self._to_str_columns()
515515

516+
if self.index and isinstance(self.frame.index, MultiIndex):
517+
fmt = self._get_formatter('__index__')
518+
clevels = self.frame.columns.nlevels
519+
strcols.pop(0)
520+
name = any(self.frame.columns.names)
521+
for i, lev in enumerate(self.frame.index.levels):
522+
lev2 = lev.format(name=name)
523+
width = len(lev2[0])
524+
lev3 = [' ' * width] * clevels + lev2
525+
strcols.insert(i, lev3)
526+
516527
if column_format is None:
517528
dtypes = self.frame.dtypes.values
529+
column_format = ''.join(map(get_col_type, dtypes))
518530
if self.index:
519-
column_format = 'l%s' % ''.join(map(get_col_type, dtypes))
520-
else:
521-
column_format = '%s' % ''.join(map(get_col_type, dtypes))
531+
index_format = 'l' * self.frame.index.nlevels
532+
column_format = index_format + column_format
522533
elif not isinstance(column_format,
523534
compat.string_types): # pragma: no cover
524535
raise AssertionError('column_format must be str or unicode, not %s'
@@ -645,8 +656,8 @@ def has_index_names(self):
645656
def has_column_names(self):
646657
return _has_names(self.frame.columns)
647658

648-
def _get_formatted_index(self,frame):
649-
# Note: this is only used by to_string(), not by to_html().
659+
def _get_formatted_index(self, frame):
660+
# Note: this is only used by to_string() and to_latex(), not by to_html().
650661
index = frame.index
651662
columns = frame.columns
652663

pandas/tests/test_format.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2098,11 +2098,11 @@ def test_to_latex_multiindex(self):
20982098
self.assertEqual(result, expected)
20992099

21002100
result = df.T.to_latex()
2101-
expected = r"""\begin{tabular}{ll}
2101+
expected = r"""\begin{tabular}{lll}
21022102
\toprule
2103-
{} & 0 \\
2103+
& & 0 \\
21042104
\midrule
2105-
x y & a \\
2105+
x & y & a \\
21062106
\bottomrule
21072107
\end{tabular}
21082108
"""

0 commit comments

Comments
 (0)