大Python乳胶产量的中间法则

2024-04-20 12:59:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我用的是Python熊猫。在

我正在尝试从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()命令从该命令创建booktab表,这很好。在

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


Tags: to数据命令脚本pandasdate规则excel
2条回答

由于pandas的^{}似乎没有提供这样一个选项,我将通过一些字符串处理手动执行此操作:

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的乳胶输出:

^{pr2}$

手动添加\midrule的输出:

^{3}$

将接受的答案放入一个函数中,以满足任何需要。在

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', '')

相关问题 更多 >