我正在使用Python Pandas。
我试图从excel工作簿中自动创建LaTeX表。到目前为止,我已完成脚本以创建以下数据帧:
Date Factor A Factor B Total
Person A 01/01/2015 A C $220m
Person B 01/02/2015 B D $439m
Total $659m
我可以使用Pandas .to_latex()
命令从中创建一个booktabs表,这一切都很好。
我的问题是,是否可以在上面数据帧的最后一行之前添加一个中间规则到LaTeX输出?
答案 0 :(得分:5)
由于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)
乳胶输出没有额外的\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}
答案 1 :(得分:0)
将接受的答案放入需要的功能中。
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', '')