Skip to content

Commit ff0f8ba

Browse files
authored
fix bug and include test (#45157)
Co-authored-by: JHM Darbyshire (MBP) <[email protected]>
1 parent 56b637e commit ff0f8ba

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

pandas/io/formats/style_render.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -748,16 +748,17 @@ def _translate_latex(self, d: dict) -> None:
748748
- Remove hidden indexes or reinsert missing th elements if part of multiindex
749749
or multirow sparsification (so that \multirow and \multicol work correctly).
750750
"""
751+
index_levels = self.index.nlevels
752+
visible_index_levels = index_levels - sum(self.hide_index_)
751753
d["head"] = [
752754
[
753-
{**col, "cellstyle": self.ctx_columns[r, c - self.index.nlevels]}
755+
{**col, "cellstyle": self.ctx_columns[r, c - visible_index_levels]}
754756
for c, col in enumerate(row)
755757
if col["is_visible"]
756758
]
757759
for r, row in enumerate(d["head"])
758760
]
759761
body = []
760-
index_levels = self.data.index.nlevels
761762
for r, row in zip(
762763
[r for r in range(len(self.data.index)) if r not in self.hidden_rows],
763764
d["body"],

pandas/tests/io/formats/style/test_to_latex.py

+23
Original file line numberDiff line numberDiff line change
@@ -853,3 +853,26 @@ def test_rendered_links():
853853
df = DataFrame(["text www.domain.com text"])
854854
result = df.style.format(hyperlinks="latex").to_latex()
855855
assert r"text \href{www.domain.com}{www.domain.com} text" in result
856+
857+
858+
def test_apply_index_hidden_levels():
859+
# gh 45156
860+
styler = DataFrame(
861+
[[1]],
862+
index=MultiIndex.from_tuples([(0, 1)], names=["l0", "l1"]),
863+
columns=MultiIndex.from_tuples([(0, 1)], names=["c0", "c1"]),
864+
).style
865+
styler.hide(level=1)
866+
styler.applymap_index(lambda v: "color: red;", level=0, axis=1)
867+
result = styler.to_latex(convert_css=True)
868+
expected = dedent(
869+
"""\
870+
\\begin{tabular}{lr}
871+
c0 & \\color{red} 0 \\\\
872+
c1 & 1 \\\\
873+
l0 & \\\\
874+
0 & 1 \\\\
875+
\\end{tabular}
876+
"""
877+
)
878+
assert result == expected

0 commit comments

Comments
 (0)