Skip to content

Commit cfdae80

Browse files
committed
Merge pull request #8219 from hayd/latex_mi_index
ENH to_latex mi index will use & sep for levels
2 parents 79c4413 + b576b35 commit cfdae80

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
@@ -514,12 +514,23 @@ def get_col_type(dtype):
514514
else:
515515
strcols = self._to_str_columns()
516516

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

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

pandas/tests/test_format.py

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

21072107
result = df.T.to_latex()
2108-
expected = r"""\begin{tabular}{ll}
2108+
expected = r"""\begin{tabular}{lll}
21092109
\toprule
2110-
{} & 0 \\
2110+
& & 0 \\
21112111
\midrule
2112-
x y & a \\
2112+
x & y & a \\
21132113
\bottomrule
21142114
\end{tabular}
21152115
"""

0 commit comments

Comments
 (0)