I have obviously seen How to print a single backslash? and related duplicates can't print '\' (single backslash) in Python, How to print a single backslash in python in a string?, Quoting backslashes in Python string literals.
But I think my issue is that I have pandas involved and it is not generating the right latex table I need. I get:
Initialization Test Accuracy
0 Random 0.200+-0.029
1 Random2 0.200+-0.0
\begin{tabular}{ll}
\toprule
Initialization & Test Accuracy \\
\midrule
Random & 0.200\textbackslash pm0.029 \\
Random2 & 0.200\textbackslash pm0.0 \\
\bottomrule
\end{tabular}
but I need:
Initialization Test Accuracy
0 Random 0.200+-0.029
1 Random2 0.200+-0.0
\begin{tabular}{ll}
\toprule
Initialization & Test Accuracy \\
\midrule
Random & 0.200 \pm 0.029 \\
Random2 & 0.200 \pm 0.0 \\
\bottomrule
\end{tabular}
how do I have pandas print the right latex table for me?
full script:
import pandas as pd
# data = {'first_column': ['first_value', 'second_value', ...],
# 'second_column': ['first_value', 'second_value', ...],
# ....
# }
import pandas as pd
#from uutils import put_pm_to_pandas_data
def put_pm_to_pandas_data(data: dict) -> dict:
"""
Change the +- to \pm for latex display.
ref:
- https://stackoverflow.com/questions/70008992/how-to-print-a-literal-backslash-to-get-pm-in-a-pandas-data-frame-to-generate-a
"""
for column_name, data_values in data.items():
# data[column_name] = [data_value.replace('+-', r'\pm') for data_value in data_values]
data[column_name] = [data_value.replace('+-', r'\\pm') for data_value in data_values]
# data[column_name] = [data_value.replace('+-', '\pm') for data_value in data_values]
return data
data = {
'Initialization': ['Random',
'Random2',
],
'Test Accuracy': ['0.200+-0.029',
'0.200+-0.0',
],
}
df = pd.DataFrame(data)
print(df)
data = put_pm_to_pandas_data(data)
df = pd.DataFrame(data)
print(df.to_latex(index=False))