BML*_*L91 3 python latex pandas
我正在使用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
Run Code Online (Sandbox Code Playgroud)
我可以使用Pandas .to_latex()命令从这里创建一个booktabs表,这很好.
我的问题是,是否可以在上面的数据帧的最后一行之前添加一个中间规则到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)
Run Code Online (Sandbox Code Playgroud)
没有额外的乳胶输出\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}
Run Code Online (Sandbox Code Playgroud)
手动添加输出\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}
Run Code Online (Sandbox Code Playgroud)
将接受的答案放入一个函数中,供任何需要它的人使用。
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', '')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1290 次 |
| 最近记录: |