Skip to content

Commit b8ca0db

Browse files
committed
FIX: Resolve KeyError with LaTeX headers in to_latex method
1 parent 2a10e04 commit b8ca0db

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

pandas/io/formats/style_render.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1564,7 +1564,12 @@ def relabel_index(
15641564
levels_ = refactor_levels(level, obj)
15651565

15661566
def alias_(x, value):
1567+
"""
1568+
Checks and returns formatted values based on specific conditions.
1569+
"""
15671570
if isinstance(value, str):
1571+
if value.startswith("$") and value.endswith("$"):
1572+
return value
15681573
return value.format(x)
15691574
return value
15701575

pandas/tests/io/formats/test_to_latex.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,30 @@ def test_to_latex_number_of_items_in_header_missmatch_raises(
370370
msg = f"Writing 2 cols but got {num_aliases} aliases"
371371
with pytest.raises(ValueError, match=msg):
372372
df.to_latex(header=header)
373+
374+
def test_to_latex_with_latex_header(self):
375+
376+
df = DataFrame({"a": [1, 2]})
377+
result = df.to_latex(header=[r"$\bar{y}$"], index=False, column_format="l")
378+
expected = r"""
379+
\begin{tabular}{l}
380+
\toprule
381+
$\bar{y}$ \\
382+
\midrule
383+
1 \\
384+
2 \\
385+
\bottomrule
386+
\end{tabular}
387+
"""
388+
# Function to remove leading spaces from each line
389+
def remove_leading_spaces(s):
390+
return '\n'.join(line.lstrip() for line in s.strip().split('\n'))
391+
392+
# Normalize both result and expected strings
393+
result_clean = remove_leading_spaces(result)
394+
expected_clean = remove_leading_spaces(expected)
395+
396+
assert result_clean == expected_clean, f"Result:\n{repr(result)}\nExpected:\n{repr(expected)}"
373397

374398
def test_to_latex_decimal(self):
375399
# GH 12031

0 commit comments

Comments
 (0)