Description
Pandas version checks
-
I have checked that this issue has not already been reported.
-
I have confirmed this bug exists on the latest version of pandas.
-
I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
import pandas as pd
pd.DataFrame({'_A': [1], '_B': ['a']}).set_index("_A").to_latex(escape=True)
# produces:
'\\begin{tabular}{ll}\n\\toprule\n & \\_B \\\\\n_A & \\\\\n\\midrule\n1 & a \\\\\n\\bottomrule\n\\end{tabular}\n'
Issue Description
The resulting table includes the raw index name, instead of escaping properly.
Expected Behavior
import pandas as pd
pd.DataFrame({'_A': [1], '_B': ['a']}).set_index("_A").to_latex(escape=True)
>>'\\begin{tabular}{ll}\n\\toprule\n & \\_B \\\\\n\_A & \\\\\n\\midrule\n1 & a \\\\\n\\bottomrule\n\\end{tabular}\n'
Installed Versions
INSTALLED VERSIONS
commit : f538741
python : 3.10.8.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.22631
machine : AMD64
processor : Intel64 Family 6 Model 183 Stepping 1, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : de_DE.cp1252
pandas : 2.2.0
numpy : 1.26.2
pytz : 2023.3.post1
dateutil : 2.8.2
setuptools : 69.0.3
pip : 23.1.2
Cython : None
pytest : 8.0.0
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 5.0.1
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.20.0
pandas_datareader : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : 4.12.2
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : 2023.12.2
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.11.4
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.4
qtpy : None
pyqt5 : None