Skip to content

Fixed latex output for multi-indexed dataframes - GH9778 #9908

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 16, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v0.16.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,5 @@ Bug Fixes
- Bug where dividing a dataframe containing values of type ``Decimal`` by another ``Decimal`` would raise. (:issue:`9787`)
- Bug where using DataFrames asfreq would remove the name of the index. (:issue:`9885`)
- 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`)

- Fixed latex output for multi-indexed dataframes (:issue:`9778`)
8 changes: 6 additions & 2 deletions pandas/core/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -613,8 +613,12 @@ def get_col_type(dtype):
name = any(self.frame.columns.names)
for i, lev in enumerate(self.frame.index.levels):
lev2 = lev.format(name=name)
width = len(lev2[0])
lev3 = [' ' * width] * clevels + lev2
blank = ' ' * len(lev2[0])
lev3 = [blank] * clevels
for level_idx, group in itertools.groupby(
self.frame.index.labels[i]):
count = len(list(group))
lev3.extend([lev2[level_idx]] + [blank] * (count - 1))
strcols.insert(i, lev3)

if column_format is None:
Expand Down
22 changes: 22 additions & 0 deletions pandas/tests/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -2194,6 +2194,28 @@ def test_to_latex_multiindex(self):
x & y & a \\
\bottomrule
\end{tabular}
"""
self.assertEqual(result, expected)

df = DataFrame.from_dict({
('c1', 0): pd.Series(dict((x, x) for x in range(4))),
('c1', 1): pd.Series(dict((x, x + 4) for x in range(4))),
('c2', 0): pd.Series(dict((x, x) for x in range(4))),
('c2', 1): pd.Series(dict((x, x + 4) for x in range(4))),
('c3', 0): pd.Series(dict((x, x) for x in range(4))),
}).T
result = df.to_latex()
expected = r"""\begin{tabular}{llrrrr}
\toprule
& & 0 & 1 & 2 & 3 \\
\midrule
c1 & 0 & 0 & 1 & 2 & 3 \\
& 1 & 4 & 5 & 6 & 7 \\
c2 & 0 & 0 & 1 & 2 & 3 \\
& 1 & 4 & 5 & 6 & 7 \\
c3 & 0 & 0 & 1 & 2 & 3 \\
\bottomrule
\end{tabular}
"""
self.assertEqual(result, expected)

Expand Down