【问题标题】:Pandas DataFrames to_latex: how to fit tables on a page?Pandas DataFrame to_latex:如何在页面上放置表格?
【发布时间】:2013-07-17 08:16:26
【问题描述】:

我正在尝试使用 pandas to_latex() 函数来创建带有我的表格的 PDF,但每次我尝试都会得到一个

第 1--43 行的段落中的 \hbox(914.42409pt 太宽)溢出

或类似错误。我知道这是因为我的表格对于页面来说太大了,我的问题是,如何让我的表格变小? to_latex 函数的文档似乎不是很广泛,所以我对解决方案的搜索并不是很有成果。

我创建表格和 .tex 文件的代码是这样的:

r = r.to_latex(na_rep = '0', float_format = fp(2),  formatters=format_dict)
message = "\documentclass[12pt]{article}" \
      "\\"+"begin{document} " \
      "\section{20 Day Trading Stats}"
footer = "\end{document}"
message = message + r + footer
afile=open("outputfile.tex", "wb")
afile.write(message)

其中fp(2)format_dict 只是参数的格式规范。

如果重要的话,我正在使用 MikTeX 和 LED 来构建 PDF,并且我的 PC 运行的是 Windows 7。

【问题讨论】:

    标签: python python-2.7 latex pandas


    【解决方案1】:

    一个解决方案可能是matrix2latex。该模块允许您将表格放置在您喜欢的任何类型的环境中。通常,我会选择:

    from matrix2latex import matrix2latex
    import numpy
    data = numpy.array(r)
    matrix2latex(data, 'outputfile.tex', 'table', 'tabular', 'small')
    

    这将导致:

    \begin{table}[ht]
    \begin{tabular}{cc...cc}
    \toprule
    \begin{small}
    item1 & item2 &..... \\
    ...
    \end{small}
    \end{tabular}
    \end{table}
    

    显然,您可以将“小”更改为您想要的任何内容,但请记住,参数的顺序很重要。

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      解决您的问题的另一种方法是在 \begin{table} 中添加 \small。您可以使用以下代码来实现:

      df.to_latex(
              os.path.join("file.tex"),
              caption="My caption",
              label="tab:subject_info",
              escape=False,
              column_format="cccccccccccccccc",
              index=False,
          )
      
      with open("file.tex"), "r+") as f:
          text = f.read().replace("\\begin{tabular}", "\small \\begin{tabular}")
          f.seek(0)
          f.write(text)
          f.close()
      

      【讨论】:

        猜你喜欢
        • 2022-01-09
        • 1970-01-01
        • 2017-04-05
        • 1970-01-01
        • 1970-01-01
        • 2023-01-12
        • 1970-01-01
        • 2014-11-18
        • 1970-01-01
        相关资源
        最近更新 更多