Skip to content

ENH: Styler.apply(map)_index made compatible with Styler.to_latex #41993

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 32 commits into from
Aug 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
ece8855
add apply across index
attack68 Jun 9, 2021
a3a88e5
add applymap across index
attack68 Jun 9, 2021
066e4f3
improve docs
attack68 Jun 9, 2021
50dbcc7
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jun 11, 2021
ef5839f
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jun 12, 2021
5e4c1c0
add column header styling and amend tests
attack68 Jun 12, 2021
20ac7e0
doc sharing
attack68 Jun 13, 2021
26c5340
doc fix
attack68 Jun 13, 2021
2437b72
doc fix
attack68 Jun 13, 2021
312a6e6
collapse the cellstyle maps
attack68 Jun 13, 2021
553426f
add basic test
attack68 Jun 13, 2021
f01dfee
add basic test
attack68 Jun 13, 2021
f940165
parametrise tests
attack68 Jun 13, 2021
6f5b46c
test for raises ValueError
attack68 Jun 13, 2021
75cf6ca
test html working
attack68 Jun 13, 2021
d654139
test html working
attack68 Jun 13, 2021
728091a
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jun 14, 2021
17787ef
whats new 1.4.0
attack68 Jun 14, 2021
c9882aa
make apply_header compatible with to_latex
attack68 Jun 14, 2021
248de0d
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jun 20, 2021
bf6cd10
Merge branch 'styler_apply_index_specific' into styler_apply_index_sp…
attack68 Jun 20, 2021
321458e
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jun 29, 2021
3d2e4bd
Merge branch 'styler_apply_index_specific' into styler_apply_index_sp…
attack68 Jun 29, 2021
ed58798
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jul 13, 2021
b58fc55
Merge branch 'styler_apply_index_specific' into styler_apply_index_sp…
attack68 Jul 13, 2021
8d8e88f
update tests
attack68 Jul 14, 2021
e17d766
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jul 30, 2021
e0cec44
Merge branch 'styler_apply_index_specific' into styler_apply_index_sp…
attack68 Jul 30, 2021
f70bf65
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Aug 6, 2021
42457de
Merge branch 'styler_apply_index_specific' into styler_apply_index_sp…
attack68 Aug 6, 2021
7ede8cc
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Aug 12, 2021
57ce478
format tests
attack68 Aug 12, 2021
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: 1 addition & 1 deletion doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Other enhancements
- :meth:`Series.ewm`, :meth:`DataFrame.ewm`, now support a ``method`` argument with a ``'table'`` option that performs the windowing operation over an entire :class:`DataFrame`. See :ref:`Window Overview <window.overview>` for performance and functional benefits (:issue:`42273`)
- Added ``sparse_index`` and ``sparse_columns`` keyword arguments to :meth:`.Styler.to_html` (:issue:`41946`)
- Added keyword argument ``environment`` to :meth:`.Styler.to_latex` also allowing a specific "longtable" entry with a separate jinja2 template (:issue:`41866`)
- :meth:`.Styler.apply_index` and :meth:`.Styler.applymap_index` added to allow conditional styling of index and column header values (:issue:`41893`)
- :meth:`.Styler.apply_index` and :meth:`.Styler.applymap_index` added to allow conditional styling of index and column header values for HTML and LaTeX (:issue:`41893`)
- :meth:`.GroupBy.cummin` and :meth:`.GroupBy.cummax` now support the argument ``skipna`` (:issue:`34047`)
-

Expand Down
27 changes: 15 additions & 12 deletions pandas/io/formats/style_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,7 +570,14 @@ 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).
"""
d["head"] = [[col for col in row if col["is_visible"]] for row in d["head"]]
d["head"] = [
[
{**col, "cellstyle": self.ctx_columns[r, c - self.index.nlevels]}
for c, col in enumerate(row)
if col["is_visible"]
]
for r, row in enumerate(d["head"])
]
body = []
for r, row in enumerate(d["body"]):
if all(self.hide_index_):
Expand All @@ -582,8 +589,9 @@ def _translate_latex(self, d: dict) -> None:
"display_value": col["display_value"]
if col["is_visible"]
else "",
"cellstyle": self.ctx_index[r, c] if col["is_visible"] else [],
}
for col in row
for c, col in enumerate(row)
if col["type"] == "th"
]

Expand Down Expand Up @@ -1378,26 +1386,21 @@ def _parse_latex_header_span(
>>> _parse_latex_header_span(cell, 't', 'c')
'\\multicolumn{3}{c}{text}'
"""
display_val = _parse_latex_cell_styles(cell["cellstyle"], cell["display_value"])
if "attributes" in cell:
attrs = cell["attributes"]
if 'colspan="' in attrs:
colspan = attrs[attrs.find('colspan="') + 9 :] # len('colspan="') = 9
colspan = int(colspan[: colspan.find('"')])
return (
f"\\multicolumn{{{colspan}}}{{{multicol_align}}}"
f"{{{cell['display_value']}}}"
)
return f"\\multicolumn{{{colspan}}}{{{multicol_align}}}{{{display_val}}}"
elif 'rowspan="' in attrs:
rowspan = attrs[attrs.find('rowspan="') + 9 :]
rowspan = int(rowspan[: rowspan.find('"')])
return (
f"\\multirow[{multirow_align}]{{{rowspan}}}{{*}}"
f"{{{cell['display_value']}}}"
)
return f"\\multirow[{multirow_align}]{{{rowspan}}}{{*}}{{{display_val}}}"
if wrap:
return f"{{{cell['display_value']}}}"
return f"{{{display_val}}}"
else:
return cell["display_value"]
return display_val


def _parse_latex_options_strip(value: str | int | float, arg: str) -> str:
Expand Down
46 changes: 43 additions & 3 deletions pandas/tests/io/formats/style/test_to_latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,17 +414,20 @@ def test_parse_latex_cell_styles_braces(wrap_arg, expected):


def test_parse_latex_header_span():
cell = {"attributes": 'colspan="3"', "display_value": "text"}
cell = {"attributes": 'colspan="3"', "display_value": "text", "cellstyle": []}
expected = "\\multicolumn{3}{Y}{text}"
assert _parse_latex_header_span(cell, "X", "Y") == expected

cell = {"attributes": 'rowspan="5"', "display_value": "text"}
cell = {"attributes": 'rowspan="5"', "display_value": "text", "cellstyle": []}
expected = "\\multirow[X]{5}{*}{text}"
assert _parse_latex_header_span(cell, "X", "Y") == expected

cell = {"display_value": "text"}
cell = {"display_value": "text", "cellstyle": []}
assert _parse_latex_header_span(cell, "X", "Y") == "text"

cell = {"display_value": "text", "cellstyle": [("bfseries", "--rwrap")]}
assert _parse_latex_header_span(cell, "X", "Y") == "\\bfseries{text}"


def test_parse_latex_table_wrapping(styler):
styler.set_table_styles(
Expand Down Expand Up @@ -635,3 +638,40 @@ def test_longtable_caption_label(styler, caption, cap_exp, label, lab_exp):
assert expected in styler.to_latex(
environment="longtable", caption=caption, label=label
)


@pytest.mark.parametrize("index", [True, False])
@pytest.mark.parametrize("columns", [True, False])
def test_apply_map_header_render_mi(df, index, columns):
cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])
ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
df.loc[2, :] = [2, -2.22, "de"]
df = df.astype({"A": int})
df.index, df.columns = ridx, cidx
styler = df.style

func = lambda v: "bfseries: --rwrap" if "A" in v or "Z" in v or "c" in v else None

if index:
styler.applymap_index(func, axis="index")
if columns:
styler.applymap_index(func, axis="columns")

result = styler.to_latex()

expected_index = dedent(
"""\
\\multirow[c]{2}{*}{\\bfseries{A}} & a & 0 & -0.610000 & ab \\\\
& b & 1 & -1.220000 & cd \\\\
B & \\bfseries{c} & 2 & -2.220000 & de \\\\
"""
)
assert (expected_index in result) is index

expected_columns = dedent(
"""\
{} & {} & \\multicolumn{2}{r}{\\bfseries{Z}} & {Y} \\\\
{} & {} & {a} & {b} & {\\bfseries{c}} \\\\
"""
)
assert (expected_columns in result) is columns