Skip to content

Commit

Permalink
BUG: to_latex() output broken when the index has a name pandas-dev#10660
Browse files Browse the repository at this point in the history
  • Loading branch information
taeold committed Oct 5, 2015
1 parent 0cd6734 commit f5efd3b
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.17.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,4 @@ Performance Improvements

Bug Fixes
~~~~~~~~~
Bug in ``.to_latex()`` output broken when the index has a name (:issue: `10660`)
8 changes: 6 additions & 2 deletions pandas/core/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -636,11 +636,13 @@ def get_col_type(dtype):
if self.index and isinstance(self.frame.index, MultiIndex):
clevels = self.frame.columns.nlevels
strcols.pop(0)
name = any(self.frame.columns.names)
name = any(self.frame.index.names)
for i, lev in enumerate(self.frame.index.levels):
lev2 = lev.format(name=name)
lev2 = lev.format()
blank = ' ' * len(lev2[0])
lev3 = [blank] * clevels
if name:
lev3.append(lev.name)
for level_idx, group in itertools.groupby(
self.frame.index.labels[i]):
count = len(list(group))
Expand All @@ -667,6 +669,8 @@ def write(buf, frame, column_format, strcols, longtable=False):
buf.write('\\toprule\n')

nlevels = frame.columns.nlevels
if any(frame.index.names):
nlevels += 1
for i, row in enumerate(zip(*strcols)):
if i == nlevels:
buf.write('\\midrule\n') # End of header
Expand Down
44 changes: 44 additions & 0 deletions pandas/tests/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -2645,6 +2645,50 @@ def test_to_latex_multiindex(self):
c3 & 0 & 0 & 1 & 2 & 3 \\
\bottomrule
\end{tabular}
"""
self.assertEqual(result, expected)

# GH 10660
df = pd.DataFrame({'a':[0,0,1,1], 'b':list('abab'), 'c':[1,2,3,4]})
result = df.set_index(['a', 'b']).to_latex()
expected = r"""\begin{tabular}{llr}
\toprule
& & c \\
a & b & \\
\midrule
0 & a & 1 \\
& b & 2 \\
1 & a & 3 \\
& b & 4 \\
\bottomrule
\end{tabular}
"""
self.assertEqual(result, expected)

result = df.groupby('a').describe().to_latex()
expected = r"""\begin{tabular}{llr}
\toprule
& & c \\
a & {} & \\
\midrule
0 & count & 2.000000 \\
& mean & 1.500000 \\
& std & 0.707107 \\
& min & 1.000000 \\
& 25\% & 1.250000 \\
& 50\% & 1.500000 \\
& 75\% & 1.750000 \\
& max & 2.000000 \\
1 & count & 2.000000 \\
& mean & 3.500000 \\
& std & 0.707107 \\
& min & 3.000000 \\
& 25\% & 3.250000 \\
& 50\% & 3.500000 \\
& 75\% & 3.750000 \\
& max & 4.000000 \\
\bottomrule
\end{tabular}
"""
self.assertEqual(result, expected)

Expand Down

0 comments on commit f5efd3b

Please sign in to comment.