Created
August 2, 2024 09:56
-
-
Save farzadhallaji/1da6930f41207f081b0502128e204dd9 to your computer and use it in GitHub Desktop.
customizable function to covert pandas dataframe to latex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
def df_to_latex(df, table_caption, table_label): | |
# Start building the LaTeX table string | |
latex_str = r""" | |
\renewcommand{\arraystretch}{1.5} % Adjust this value to change the row height | |
\begin{table}[h!] | |
\centering | |
\begin{adjustbox}{max width=\textwidth, center} % Fit table to page width and center it | |
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|} | |
\hline | |
\multirow{2}{*}{Dataset} & \multirow{2}{*}{Supervised} & \multirow{2}{*}{S-SSL} & \multicolumn{6}{c|}{SSL with Conformal Prediction} & \multirow{2}{*}{Fully} \\ \cline{4-9} | |
& & & SSL-ICP & SSL-CCP & SSL-BCP & SSL ACP-C & SSL ACP-B & SSL ACP-R & \\ | |
\hline | |
""" | |
for i, row in df.iterrows(): | |
r = [i] + list(row.values) | |
r = [f"{x:.2f}" if isinstance(x, (int, float)) else str(x) for x in r] | |
latex_str += " & ".join(r) + r" \\" + "\n" + r"\hline" + "\n" | |
# Finish the table | |
latex_str += r""" | |
\end{tabular} | |
\end{adjustbox} | |
\caption{""" + table_caption + r"""} | |
\label{""" + table_label + r"""} | |
\end{table} | |
""" | |
return latex_str | |
def create_tex_file(csv_path): | |
table_caption = 'Table Caption' | |
table_label = f"tab:{csv_path.replace('.csv', '')}" | |
output_path = csv_path.replace('csv', 'tex') | |
df = pd.read_csv(csv_path, index_col=0).loc[data_names+['aveg.']] | |
df.rename(index={d:d.replace('rman_s', 'rman\'s').replace('-', ' ').replace('_', ' ').replace('aveg.', 'avg.') for d in data_names+['aveg.']}, inplace=True) | |
latex_code = df_to_latex(df, table_caption, table_label) | |
with open(output_path, 'w') as f: | |
f.write(latex_code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment