Skip to content

Commit 1517662

Browse files
committed
FIX: Resolve KeyError with LaTeX headers in to_latex method
- Fixed an issue with LaTeX headers by preventing format interpretation in style_render.py. - Added test cases to validate proper handling of LaTeX headers without index columns.
1 parent 2a10e04 commit 1517662

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
@@ -371,6 +371,30 @@ def test_to_latex_number_of_items_in_header_missmatch_raises(
371371
with pytest.raises(ValueError, match=msg):
372372
df.to_latex(header=header)
373373

374+
def test_to_latex_with_latex_header(self):
375+
df = DataFrame({"a": [1, 2]})
376+
result = df.to_latex(header=[r"$\bar{y}$"], index=False, column_format="l")
377+
expected = r"""
378+
\begin{tabular}{l}
379+
\toprule
380+
$\bar{y}$ \\
381+
\midrule
382+
1 \\
383+
2 \\
384+
\bottomrule
385+
\end{tabular}
386+
"""
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
397+
374398
def test_to_latex_decimal(self):
375399
# GH 12031
376400
df = DataFrame({"a": [1.0, 2.1], "b": ["b1", "b2"]})

0 commit comments

Comments
 (0)