Skip to content

Commit 6695c25

Browse files
committed
Fixed latex output for multi-indexed dataframes - GH9778
1 parent 8cbb579 commit 6695c25

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

pandas/core/format.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -613,8 +613,12 @@ def get_col_type(dtype):
613613
name = any(self.frame.columns.names)
614614
for i, lev in enumerate(self.frame.index.levels):
615615
lev2 = lev.format(name=name)
616-
width = len(lev2[0])
617-
lev3 = [' ' * width] * clevels + lev2
616+
blank = ' ' * len(lev2[0])
617+
lev3 = [blank] * clevels
618+
for level_idx, group in itertools.groupby(
619+
self.frame.index.labels[i]):
620+
count = len(list(group))
621+
lev3.extend([lev2[level_idx]] + [blank] * (count - 1))
618622
strcols.insert(i, lev3)
619623

620624
if column_format is None:

pandas/tests/test_format.py

+22
Original file line numberDiff line numberDiff line change
@@ -2194,6 +2194,28 @@ def test_to_latex_multiindex(self):
21942194
x & y & a \\
21952195
\bottomrule
21962196
\end{tabular}
2197+
"""
2198+
self.assertEqual(result, expected)
2199+
2200+
df = DataFrame.from_dict({
2201+
('c1', 0): pd.Series({x: x for x in range(4)}),
2202+
('c1', 1): pd.Series({x: x+4 for x in range(4)}),
2203+
('c2', 0): pd.Series({x: x for x in range(4)}),
2204+
('c2', 1): pd.Series({x: x+4 for x in range(4)}),
2205+
('c3', 0): pd.Series({x: x for x in range(4)}),
2206+
}).T
2207+
result = df.to_latex()
2208+
expected = r"""\begin{tabular}{llrrrr}
2209+
\toprule
2210+
& & 0 & 1 & 2 & 3 \\
2211+
\midrule
2212+
c1 & 0 & 0 & 1 & 2 & 3 \\
2213+
& 1 & 4 & 5 & 6 & 7 \\
2214+
c2 & 0 & 0 & 1 & 2 & 3 \\
2215+
& 1 & 4 & 5 & 6 & 7 \\
2216+
c3 & 0 & 0 & 1 & 2 & 3 \\
2217+
\bottomrule
2218+
\end{tabular}
21972219
"""
21982220
self.assertEqual(result, expected)
21992221

0 commit comments

Comments
 (0)