Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas to_latex(): how to make lines in tables?

Tags:

python

pandas

I'm making the latex table with pandas, like:

table.to_latex()

However,the output table doesn't contain lines, like "\hline" to make the table with actual. As far as I understand that should happen by default but it doesn't and it is not clear how to do that with options.

Any advice would be appreciated, thanks.

like image 361
Ivan Shvetsov Avatar asked Oct 19 '22 08:10

Ivan Shvetsov


1 Answers

Not that I'm particularly proud of it, but the following solution works:

def latex_with_lines(df, *args, **kwargs):
    kwargs['column_format'] = '|'.join([''] + ['l'] * df.index.nlevels
                                            + ['r'] * df.shape[1] + [''])
    res = df.to_latex(*args, **kwargs)
    return res.replace('\\\\\n', '\\\\ \\midrule\n')

(and can be easily adapted to support the buf argument to directly write to file).

Use as

latex_repr = latex_with_lines(df)
like image 158
Pietro Battiston Avatar answered Nov 01 '22 11:11

Pietro Battiston