Skip to content

Commit 7b0c554

Browse files
Maximilian Köstlergfyoung
Maximilian Köstler
authored andcommitted
BUG: LatexFormatter.write_result multi-index
Fixed GH issue 14484: `LatexFormatter.write_result`` now does not print blanks if a higher-order index differs from the previous row. Also added testcase for this.
1 parent ba3a442 commit 7b0c554

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

pandas/io/formats/format.py

+13-5
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@
4646
import pandas as pd
4747
import numpy as np
4848

49-
import itertools
5049
import csv
5150
from functools import partial
5251

@@ -903,6 +902,7 @@ def get_col_type(dtype):
903902
name = any(self.frame.index.names)
904903
cname = any(self.frame.columns.names)
905904
lastcol = self.frame.index.nlevels - 1
905+
previous_lev3 = None
906906
for i, lev in enumerate(self.frame.index.levels):
907907
lev2 = lev.format()
908908
blank = ' ' * len(lev2[0])
@@ -913,11 +913,19 @@ def get_col_type(dtype):
913913
lev3 = [blank] * clevels
914914
if name:
915915
lev3.append(lev.name)
916-
for level_idx, group in itertools.groupby(
917-
self.frame.index.labels[i]):
918-
count = len(list(group))
919-
lev3.extend([lev2[level_idx]] + [blank] * (count - 1))
916+
current_idx_val = None
917+
for level_idx in self.frame.index.labels[i]:
918+
if ((previous_lev3 is None or
919+
previous_lev3[len(lev3)].isspace()) and
920+
lev2[level_idx] == current_idx_val):
921+
# same index as above row and left index was the same
922+
lev3.append(blank)
923+
else:
924+
# different value than above or left index different
925+
lev3.append(lev2[level_idx])
926+
current_idx_val = lev2[level_idx]
920927
strcols.insert(i, lev3)
928+
previous_lev3 = lev3
921929

922930
column_format = self.column_format
923931
if column_format is None:

pandas/tests/io/formats/test_to_latex.py

+22
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,28 @@ def test_to_latex_multiindex(self):
217217
1 & 2.0 & 3.5 & 0.707107 & 3.0 & 3.25 & 3.5 & 3.75 & 4.0 \\
218218
\bottomrule
219219
\end{tabular}
220+
"""
221+
222+
assert result == expected
223+
224+
# GH 14484
225+
# If an index is repeated in subsequent rows, it should be
226+
# replaced with a blank in the created table.
227+
# This should ONLY happen if all higher order indicies
228+
# (to the left) are equal, too.
229+
# In this test, 'c' has to be printed both times, because
230+
# the higher order index 'A' != 'B'
231+
df = pd.DataFrame(index=pd.MultiIndex.from_tuples(
232+
[('A', 'c'), ('B', 'c')]), columns=['col'])
233+
result = df.to_latex()
234+
expected = r"""\begin{tabular}{lll}
235+
\toprule
236+
& & col \\
237+
\midrule
238+
A & c & NaN \\
239+
B & c & NaN \\
240+
\bottomrule
241+
\end{tabular}
220242
"""
221243

222244
assert result == expected

0 commit comments

Comments
 (0)