diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 08d9fd938c873..907cce19cff55 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -1564,7 +1564,12 @@ def relabel_index( levels_ = refactor_levels(level, obj) def alias_(x, value): + """ + Checks and returns formatted values based on specific conditions. + """ if isinstance(value, str): + if value.startswith("$") and value.endswith("$"): + return value return value.format(x) return value diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index 1de53993fe646..0ea0bf77dad41 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -371,6 +371,30 @@ def test_to_latex_number_of_items_in_header_missmatch_raises( with pytest.raises(ValueError, match=msg): df.to_latex(header=header) + def test_to_latex_with_latex_header(self): + df = DataFrame({"a": [1, 2]}) + result = df.to_latex(header=[r"$\bar{y}$"], index=False, column_format="l") + expected = r""" + \begin{tabular}{l} + \toprule + $\bar{y}$ \\ + \midrule + 1 \\ + 2 \\ + \bottomrule + \end{tabular} + """ + + # Function to remove leading spaces from each line + def remove_leading_spaces(s): + return "\n".join(line.lstrip() for line in s.strip().split("\n")) + + # Normalize both result and expected strings + result_clean = remove_leading_spaces(result) + expected_clean = remove_leading_spaces(expected) + + assert result_clean == expected_clean + def test_to_latex_decimal(self): # GH 12031 df = DataFrame({"a": [1.0, 2.1], "b": ["b1", "b2"]})