Skip to content
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
11 changes: 10 additions & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3568,6 +3568,7 @@ def _wrap(x, alt_format_):
elif formatters is None and float_format is not None:
formatters_ = partial(_wrap, alt_format_=lambda v: v)
format_index_ = [index_format_, column_format_]
format_index_names_ = [index_format_, column_format_]

# Deal with hiding indexes and relabelling column names
hide_: list[dict] = []
Expand Down Expand Up @@ -3616,6 +3617,7 @@ def _wrap(x, alt_format_):
relabel_index=relabel_index_,
format={"formatter": formatters_, **base_format_},
format_index=format_index_,
format_index_names=format_index_names_,
render_kwargs=render_kwargs_,
)

Expand All @@ -3628,6 +3630,7 @@ def _to_latex_via_styler(
relabel_index: dict | list[dict] | None = None,
format: dict | list[dict] | None = None,
format_index: dict | list[dict] | None = None,
format_index_names: dict | list[dict] | None = None,
render_kwargs: dict | None = None,
):
"""
Expand Down Expand Up @@ -3672,7 +3675,13 @@ def _to_latex_via_styler(
self = cast("DataFrame", self)
styler = Styler(self, uuid="")

for kw_name in ["hide", "relabel_index", "format", "format_index"]:
for kw_name in [
"hide",
"relabel_index",
"format",
"format_index",
"format_index_names",
]:
kw = vars()[kw_name]
if isinstance(kw, dict):
getattr(styler, kw_name)(**kw)
Expand Down
40 changes: 40 additions & 0 deletions pandas/tests/io/formats/test_to_latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -824,6 +824,46 @@ def test_to_latex_escape_special_chars(self):
)
assert result == expected

def test_to_latex_escape_special_chars_in_index_names(self):
# https://github.com/pandas-dev/pandas/issues/61309
# https://github.com/pandas-dev/pandas/issues/57362
index = "&%$#_{}}~^\\"
df = DataFrame({index: [1, 2, 3]}).set_index(index)
result = df.to_latex(escape=True)
expected = _dedent(
r"""
\begin{tabular}{l}
\toprule
\&\%\$\#\_\{\}\}\textasciitilde \textasciicircum \textbackslash \\
\midrule
1 \\
2 \\
3 \\
\bottomrule
\end{tabular}
"""
)
assert result == expected

def test_to_latex_escape_special_chars_in_column_name(self):
df = DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
df.columns.name = "_^~"
result = df.to_latex(escape=True)
expected = _dedent(
r"""
\begin{tabular}{lrl}
\toprule
\_\textasciicircum \textasciitilde & A & B \\
\midrule
0 & 1 & a \\
1 & 2 & b \\
2 & 3 & c \\
\bottomrule
\end{tabular}
"""
)
assert result == expected

def test_to_latex_specified_header_special_chars_without_escape(self):
# GH 7124
df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})
Expand Down
Loading