Python Pandas 的 LaTeX 输出中的中间规则

Midrule in LaTeX output of Python Pandas

我正在使用 Python Pandas。

我正在尝试从 excel 工作簿自动创建 LaTeX tables。到目前为止,我已经完成了创建以下数据框的脚本:

            Date        Factor A    Factor B    Total
Person A    01/01/2015  A           C           0m
Person B    01/02/2015  B           D           9m
                                    Total       9m

我可以使用Pandas .to_latex()命令从中创建一个书签table,没问题。

我的问题是,是否可以在上面数据帧的最后一行之前添加一个中间规则到 LaTeX 输出?

因为 pandas' .to_latex() 似乎没有提供这样的选项,我会通过一些字符串处理手动进行此操作:

import pandas as pd
import numpy as np

# use a DataFrame df with some sample data
df = pd.DataFrame(np.random.random((5, 5)))

# get latex string via `.to_latex()`
latex = df.to_latex()

# split lines into a list
latex_list = latex.splitlines()

# insert a `\midrule` at third last position in list (which will be the fourth last line in latex output)
latex_list.insert(len(latex_list)-3, '\midrule')

# join split lines to get the modified latex output string
latex_new = '\n'.join(latex_list)

没有额外的 Latex 输出 \midrule:

\begin{tabular}{lrrrrr}
\toprule
{} &         0 &         1 &         2 &         3 &         4 \
\midrule
0 &  0.563803 &  0.962439 &  0.572583 &  0.567999 &  0.390899 \
1 &  0.728756 &  0.452122 &  0.358927 &  0.426866 &  0.234689 \
2 &  0.907841 &  0.622264 &  0.128458 &  0.098953 &  0.711350 \
3 &  0.338298 &  0.576341 &  0.625921 &  0.139799 &  0.146484 \
4 &  0.303568 &  0.495921 &  0.835966 &  0.583697 &  0.675465 \
\bottomrule
\end{tabular}

手动添加的输出\midrule:

\begin{tabular}{lrrrrr}
\toprule
{} &         0 &         1 &         2 &         3 &         4 \
\midrule
0 &  0.563803 &  0.962439 &  0.572583 &  0.567999 &  0.390899 \
1 &  0.728756 &  0.452122 &  0.358927 &  0.426866 &  0.234689 \
2 &  0.907841 &  0.622264 &  0.128458 &  0.098953 &  0.711350 \
3 &  0.338298 &  0.576341 &  0.625921 &  0.139799 &  0.146484 \
\midrule
4 &  0.303568 &  0.495921 &  0.835966 &  0.583697 &  0.675465 \
\bottomrule
\end{tabular}

将已接受的答案放入函数中供需要的人使用。

def add_hline(latex: str, index: int) -> str:
    """
    Adds a horizontal `index` lines before the last line of the table

    Args:
        latex: latex table
        index: index of horizontal line insertion (in lines)
    """
    lines = latex.splitlines()
    lines.insert(len(lines) - index - 2, r'\midrule')
    return '\n'.join(lines).replace('NaN', '')