Skip to content

Commit 4d1268e

Browse files
committed
BUG: Fixed latex output for multi-indexed dataframes - GH9778
1 parent 53bc65e commit 4d1268e

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

doc/source/whatsnew/v0.16.1.txt

+2
Original file line numberDiff line numberDiff line change
@@ -157,3 +157,5 @@ Bug Fixes
157157
- Bug where dividing a dataframe containing values of type ``Decimal`` by another ``Decimal`` would raise. (:issue:`9787`)
158158
- Bug where using DataFrames asfreq would remove the name of the index. (:issue:`9885`)
159159
- Changed caching in ``AbstractHolidayCalendar`` to be at the instance level rather than at the class level as the latter can result in unexpected behaviour. (:issue:`9552`)
160+
161+
- Fixed latex output for multi-indexed dataframes (:issue:`9778`)

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(dict((x, x) for x in range(4))),
2202+
('c1', 1): pd.Series(dict((x, x + 4) for x in range(4))),
2203+
('c2', 0): pd.Series(dict((x, x) for x in range(4))),
2204+
('c2', 1): pd.Series(dict((x, x + 4) for x in range(4))),
2205+
('c3', 0): pd.Series(dict((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)