Skip to content

BUG: Styler.apply_index fails with LaTeX conversion with hidden Multi levels #45157

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 2 commits into from
Jan 3, 2022
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
5 changes: 3 additions & 2 deletions pandas/io/formats/style_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -748,16 +748,17 @@ def _translate_latex(self, d: dict) -> None:
- Remove hidden indexes or reinsert missing th elements if part of multiindex
or multirow sparsification (so that \multirow and \multicol work correctly).
"""
index_levels = self.index.nlevels
visible_index_levels = index_levels - sum(self.hide_index_)
d["head"] = [
[
{**col, "cellstyle": self.ctx_columns[r, c - self.index.nlevels]}
{**col, "cellstyle": self.ctx_columns[r, c - visible_index_levels]}
for c, col in enumerate(row)
if col["is_visible"]
]
for r, row in enumerate(d["head"])
]
body = []
index_levels = self.data.index.nlevels
for r, row in zip(
[r for r in range(len(self.data.index)) if r not in self.hidden_rows],
d["body"],
Expand Down
23 changes: 23 additions & 0 deletions pandas/tests/io/formats/style/test_to_latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -853,3 +853,26 @@ def test_rendered_links():
df = DataFrame(["text www.domain.com text"])
result = df.style.format(hyperlinks="latex").to_latex()
assert r"text \href{www.domain.com}{www.domain.com} text" in result


def test_apply_index_hidden_levels():
# gh 45156
styler = DataFrame(
[[1]],
index=MultiIndex.from_tuples([(0, 1)], names=["l0", "l1"]),
columns=MultiIndex.from_tuples([(0, 1)], names=["c0", "c1"]),
).style
styler.hide(level=1)
styler.applymap_index(lambda v: "color: red;", level=0, axis=1)
result = styler.to_latex(convert_css=True)
expected = dedent(
"""\
\\begin{tabular}{lr}
c0 & \\color{red} 0 \\\\
c1 & 1 \\\\
l0 & \\\\
0 & 1 \\\\
\\end{tabular}
"""
)
assert result == expected