Skip to content

Commit 7a4c467

Browse files
committed
Fix DataFrame.to_latex() with MultiIndex columns
Currently, the positioning of \midrule is determined by the number of index levels, not columns levels: >>> print pd.DataFrame({('x', 'y'): ['a']}).to_latex() \begin{tabular}{ll} \toprule {} & x \\ \midrule {} & y \\ 0 & a \\ \bottomrule \end{tabular} The fix is simple: use the number of column levels instead of the number of index levels.
1 parent e800fe1 commit 7a4c467

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

doc/source/v0.15.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -429,7 +429,7 @@ Bug Fixes
429429
- ``Period`` and ``PeriodIndex`` addition/subtraction with ``np.timedelta64`` results in incorrect internal representations (:issue:`7740`)
430430

431431

432-
432+
- Bug in ``DataFrame.to_latex`` formatting when columns or index is a ``MultiIndex`` (:issue:`7982`).
433433

434434

435435

pandas/core/format.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -532,7 +532,7 @@ def write(buf, frame, column_format, strcols, longtable=False):
532532
buf.write('\\begin{longtable}{%s}\n' % column_format)
533533
buf.write('\\toprule\n')
534534

535-
nlevels = frame.index.nlevels
535+
nlevels = frame.columns.nlevels
536536
for i, row in enumerate(zip(*strcols)):
537537
if i == nlevels:
538538
buf.write('\\midrule\n') # End of header

pandas/tests/test_format.py

+25
Original file line numberDiff line numberDiff line change
@@ -2083,6 +2083,31 @@ def test_to_latex(self):
20832083
"""
20842084
self.assertEqual(withoutindex_result, withoutindex_expected)
20852085

2086+
def test_to_latex_multiindex(self):
2087+
df = DataFrame({('x', 'y'): ['a']})
2088+
result = df.to_latex()
2089+
expected = r"""\begin{tabular}{ll}
2090+
\toprule
2091+
{} & x \\
2092+
{} & y \\
2093+
\midrule
2094+
0 & a \\
2095+
\bottomrule
2096+
\end{tabular}
2097+
"""
2098+
self.assertEqual(result, expected)
2099+
2100+
result = df.T.to_latex()
2101+
expected = r"""\begin{tabular}{ll}
2102+
\toprule
2103+
{} & 0 \\
2104+
\midrule
2105+
x y & a \\
2106+
\bottomrule
2107+
\end{tabular}
2108+
"""
2109+
self.assertEqual(result, expected)
2110+
20862111
def test_to_latex_escape(self):
20872112
a = 'a'
20882113
b = 'b'

0 commit comments

Comments
 (0)