pythonpandascsvlatex

Pandas style.to_latex: how to add a \cmidrule in the header?


I have mycsv.csv:

Nr,A,B,C
1,a,b,g
2,c,d,h
3,e,f,i

With this Phyton code:

import pandas as pd

testo = pd.read_csv("mycsv.csv")
columns = [
    ('','Something'),
    ('Multicolumn','A'),
    ('Multicolumn','B'),   
    ('Something else',''),   
]
testo.columns = pd.MultiIndex.from_tuples(columns)
testo.head()
testo.style.hide(axis="index").to_latex("myout.tex",hrules=True,
                                           multicol_align='c')

I got myout.tex:

\begin{tabular}{rlll}
\toprule
 & \multicolumn{2}{c}{Multicolumn} & Something else \\
Something & A & B &  \\
\midrule
1 & a & b & g \\
2 & c & d & h \\
3 & e & f & i \\
\bottomrule
\end{tabular}

I would like to add a \cmidrule{2-3} in the headers:

\documentclass[10pt]{article}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{rlll}
\toprule
 & \multicolumn{2}{c}{Multicolumn} & Something else \\
\cmidrule{2-3}
Something & A & B &  \\
\midrule
1 & a & b & g \\
2 & c & d & h \\
3 & e & f & i \\
\bottomrule
\end{tabular}

\end{document}

How can I do it?


Solution

  • As a quick and dirty hack, one could use https://stackoverflow.com/a/32276740/2777074 to smuggle a \cmidrule{2-3} into the code:

    import pandas as pd
    import numpy as np
    
    testo = pd.read_csv("mycsv.csv")
    columns = [
        ('','Something'),
        ('Multicolumn','A'),
        ('Multicolumn','B'),   
        ('Something else',''),   
    ]
    testo.columns = pd.MultiIndex.from_tuples(columns)
    testo.head()
    latex = testo.style.hide(axis="index").to_latex(hrules=True,
                                               multicol_align='c')
    
    latex_list = latex.splitlines()
    latex_list.insert(3, '\\cmidrule{2-3}')
    
    latex_new = '\n'.join(latex_list)
    
    print(latex_new, file=open('myout.tex', 'w'))
    

    enter image description here