【问题标题】:Is there a function to format the index name in a pandas styler (DataFrame.style.to_latex) so can escape latex?是否有一个函数可以在 pandas 样式器(DataFrame.style.to_latex)中格式化索引名称,以便可以转义乳胶?
【发布时间】:2022-06-24 00:54:53
【问题描述】:

我正在尝试格式化索引名称,以便在使用 .to_latex() 时可以转义乳胶。 使用 .format_index() 仅适用于索引值,但不适用于索引名称。

这是一个最小的、可重现的示例。

import pandas as pd
import numpy as np
import pylatex as pl

dict1= {
    'employee_w': ['John_Smith','John_Smith','John_Smith', 'Marc_Jones','Marc_Jones', 'Tony_Jeff', 'Maria_Mora','Maria_Mora'],
    'customer&client': ['company_1','company_2','company_3','company_4','company_5','company_6','company_7','company_8'],
    'calendar_week': [18,18,19,21,21,22,23,23],
    'sales': [5,5,5,5,5,5,5,5],
}

df1 = pd.DataFrame(data = dict1)

ptable = pd.pivot_table(
    df1,
    values='sales',
    index=['employee_w','customer&client'],
    columns=['calendar_week'],
    aggfunc=np.sum
)

mystyler = ptable.style
mystyler.format(na_rep='-', precision=0, escape="latex") 
mystyler.format_index(escape="latex", axis=0)
mystyler.format_index(escape="latex", axis=1)

latex_code1 = mystyler.to_latex(
    column_format='|c|c|c|c|c|c|c|',
    multirow_align="t",
    multicol_align="r",
    clines="all;data",
    hrules=True,
)

# latex_code1 = latex_code1.replace("employee_w", "employee")
# latex_code1 = latex_code1.replace("customer&client", "customer and client")
# latex_code1 = latex_code1.replace("calendar_week", "week")

doc = pl.Document(geometry_options=['a4paper'], document_options=["portrait"], textcomp = None) 

doc.packages.append(pl.Package('newtxtext,newtxmath')) 
doc.packages.append(pl.Package('textcomp')) 
doc.packages.append(pl.Package('booktabs'))
doc.packages.append(pl.Package('xcolor',options= pl.NoEscape('table')))
doc.packages.append(pl.Package('multirow'))

doc.append(pl.NoEscape(latex_code1))
doc.generate_pdf('file1.pdf', clean_tex=False, silent=True)

当我使用 .replace() 替换它们时,它可以工作。例如注释行。 (期望的结果):

但我正在处理数百个索引/列名未知的表。

范围是使用 Pylatex 自动生成 PDF 文件。所以任何 html 选项对我都没有帮助。

提前致谢!

【问题讨论】:

  • 与您的问题无关,但不要将booktabs 与垂直线一起使用,这会导致所有这些差距。
  • @samcarter_is_at_topanswers.xyz 感谢您的观察。我知道现在没有人使用垂直线。但是我的同事很固执,说不能正确阅读表格,所以 vlines 必须留下。由于.to_latex 依赖于booktabs,我还没有找到其他方法。如果您知道其他方式,我会很高兴听到它:)。
  • 如果必须保留vlines,请移除booktabs包(并加载array包,这将使线接头更好):)
  • @samcarter_is_at_topanswers.xyz 成功了!没有更多的差距。我只需要在styler.set_table_styles() 内将rules 更改为hlines,不再需要booktabs。谢谢。
  • 不客气!我一直祈祷你现在也得到了你实际提出的问题的答案:)

标签: python python-3.x pandas latex pylatex


【解决方案1】:

我编码了所有Styler.to_latex 功能,恐怕索引名称当前没有格式化,这也意味着它们没有被转义。所以没有直接的功能可以做你想做的事。 (顺便说一句,很高兴看到一个例子,其中包括 hrules 表样式定义在内的许多功能正在被使用)。实际上,我刚刚在 Pandas Github 上创建了一个关于此的问题。

但是,代码本身在pandas.io.formats.styler_render.py 中包含一个_escape_latex(s) 方法

def _escape_latex(s):
    r"""
    Replace the characters ``&``, ``%``, ``$``, ``#``, ``_``, ``{``, ``}``,
    ``~``, ``^``, and ``\`` in the string with LaTeX-safe sequences.

    Use this if you need to display text that might contain such characters in LaTeX.

    Parameters
    ----------
    s : str
        Input to be escaped

    Return
    ------
    str :
        Escaped string
    """
    return (
        s.replace("\\", "ab2§=§8yz")  # rare string for final conversion: avoid \\ clash
        .replace("ab2§=§8yz ", "ab2§=§8yz\\space ")  # since \backslash gobbles spaces
        .replace("&", "\\&")
        .replace("%", "\\%")
        .replace("$", "\\$")
        .replace("#", "\\#")
        .replace("_", "\\_")
        .replace("{", "\\{")
        .replace("}", "\\}")
        .replace("~ ", "~\\space ")  # since \textasciitilde gobbles spaces
        .replace("~", "\\textasciitilde ")
        .replace("^ ", "^\\space ")  # since \textasciicircum gobbles spaces
        .replace("^", "\\textasciicircum ")
        .replace("ab2§=§8yz", "\\textbackslash ")
    )

所以最好的办法是在对输入数据框进行任何样式设置之前重新格式化输入数据框并转义索引名称:

df.index.name = _escape_latex(df.index.name)
# then continue with your previous styling code

【讨论】:

    猜你喜欢
    • 2015-01-23
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2019-12-10
    • 2020-12-30
    • 1970-01-01
    相关资源
    最近更新 更多