如何使用 nbconvert+pandoc 在 pdf 中呈现 pd.DataFrame table

How to render pd.DataFrame table in pdf with nbconvert+pandoc

我正在从一组 Jupyter 笔记本生成 pdf。对于每个 .ipynb 文件,我是 运行

$ jupyter-nbconvert --to markdown Untitled1.ipynb

然后将它们合并在一起:

$ pandoc Untitled1.md [Untitled2.md ...] -f gfm --pdf-engine=pdflatex -o all_notebooks.pdf

(我主要遵循示例 here。)我注意到的一件事是 pandas DataFrame,例如

import pandas as pd
df = pd.DataFrame({'a':[1,2,3]})
df.head()

在 pdf 中呈现为

而不是

知道如何解决这个问题吗?我正在使用 $ jupyter-nbconvert --version 5.6.1$ pandoc --version 2.9.2.1。在 md 文件中,table 变成下面的 html 块。我怀疑 pandoc 没有正确解释它。我尝试了建议的 from-markdown-strict 选项 ,但没有成功。

谢谢!

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>a</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1</td>
    </tr>
    <tr>
      <th>1</th>
      <td>2</td>
    </tr>
    <tr>
      <th>2</th>
      <td>3</td>
    </tr>
  </tbody>
</table>
</div>

问题似乎出在Jupyter和Pandoc之间的连接上。 Jupyter 没有输出格式化的 markdown,因此 pandoc 没有将其格式化为 PDF。

这里的问题是 nbconvert 将数据帧视为 HTML(加上您在输出中看到的样式,issue here),它被 pandoc 的 Markdown 转换器忽略。

解决此问题的一种方法是更改​​ pandas' 的行为,以不在笔记本中将 DataFrames 写为 HTML。您可以通过设置每个笔记本顶部的选项来做到这一点:

pd.set_option("display.notebook_repr_html", False)

另一种选择是使用 HTML 表示作为中间步骤而不是 Markdown:

$ jupyter-nbconvert --to html Untitled1.ipynb
$ pandoc Untitled1.html -t latex --pdf-engine=pdflatex -o all_notebooks.pdf

当然如果你不需要做其他格式,你可以直接将你的笔记本保存为pdf:

jupyter-nbconvert --to pdf Untitled1.ipynb

(要合并多个笔记本,请参阅讨论 here。)

对我来说最好的方法是使用 ipypublish (https://ipypublish.readthedocs.io/en/latest/)

安装

conda install -c conda-forge ipypublish

设置pandas

from ipypublish import nb_setup
pd = nb_setup.setup_pandas(escape_latex = False)
...
pd.DataFrame(mydata)

利润

jupyter nbconvert notebook.ipynb --no-input --no-prompt --to pdf

确保在转换笔记本之前再次 运行 笔记本,以便所有表格都使用 ipypublish 呈现。然后它们在笔记本和 PDF 中看起来很酷。