Last active
July 20, 2022 07:58
-
-
Save JLDC/77f4fdebe3384d55450489e579bd8768 to your computer and use it in GitHub Desktop.
pd_to_latex
This file contains 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
def pd_to_latex(df, print_index=True, out_file=None, align='r', col_sep="|", | |
digits=2, centering=True): | |
# If out_file is specified, outputs a .tex file, otherwise, just output the contents as a string | |
if len(align) == 1: # Everything is aligned the same | |
align = [align for _ in range((len(df.columns) + print_index))] | |
else: # Alignment fully specified, must match df length | |
if len(align) != len(df.columns) + print_index: | |
raise Exception("Fully specified alignment must match dataframe size") | |
align = col_sep + col_sep.join(align) + col_sep | |
# Add alignment, top border | |
output = [f"\\begin{{tabular}}{{{align}}}", "\\hline"] | |
# Add centering | |
if centering: output = ["\\begin{center}"] + output | |
# Add column names | |
output.append(" & ".join(([""] if print_index else []) + list(df.columns)) + " \\\\ [0.5ex]") | |
output.append("\\hline\\hline") | |
# Add single lines (vectorizing would be much nicer, but print_index makes it difficult) | |
for i in range(len(df)): | |
output.append(" & ".join( | |
([f"\\textbf{{{df.index[i]}}}"] if print_index else []) | |
+ [f"{x:.{digits}f}" for x in df.iloc[i]]) + " \\\\") | |
# Bottom border | |
output.append("\\hline") | |
# Replace % signs with \% | |
output = [x.replace("%", "\\%") for x in output] | |
# Close the tabular environment and return or print to file | |
output.append("\\end{tabular}") | |
# Close centering if needed | |
if centering: output.append("\\end{center}") | |
output = "\n".join(output) | |
if out_file: | |
with open(out_file, "w") as f: | |
f.write(output) | |
return | |
else: | |
return output | |
# Example usage (create file test.tex, including the index column first) | |
pd_to_latex(iris.describe(), print_index=True, out_file="test.tex") | |
# Example usage (print the string without creating any output file, excluding the index column) | |
print(pd_to_latex(iris.describe(), print_index=False)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment