Created
September 17, 2019 00:55
-
-
Save gryan11/7d3bd85426fcb6c640ec8e2db117fe16 to your computer and use it in GitHub Desktop.
Python tool for converting csvs to latex tables.
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 | |
| import numpy as np | |
| import sys, argparse | |
| from numbers import Number | |
| def df_to_latex(df, digits=2, pcols=None): | |
| table = "\\begin{tabular}{l " | |
| if pcols: | |
| for _ in range(len(df.columns)): | |
| table += "p{"+str(pcols)+"cm} " | |
| else: | |
| table += "r"*len(df.columns) | |
| table +="}\n" | |
| table += "\\toprule\n" | |
| table += '&'+'&'.join(map(lambda x: x.replace('_', '\\_'), list(df.columns))) + '\\\\' + '\n' | |
| table += "\\midrule\n" | |
| df = np.round(df, digits) | |
| for i, r in df.iterrows(): | |
| table += str(i) + '&' | |
| table += '&'.join(map(lambda x: str(x).replace('_','\\_') if isinstance(x, str) or isinstance(x, Number) and not np.isnan(x) else '-', list(r))) | |
| table += '\\\\'+'\n' | |
| table += '\\bottomrule\n' | |
| table += '\\end{tabular}\n' | |
| return table | |
| def main(argv=sys.argv[1:]): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('input_csv') | |
| parser.add_argument('-d', dest='digits', type=int, default=2) | |
| parser.add_argument('-pcols', dest='pcols', type=float) | |
| args = parser.parse_args(argv) | |
| df = pd.read_csv(args.input_csv, index_col=0) | |
| table = df_to_latex(df, args.digits, args.pcols) | |
| print(table) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment