gpt4 book ai didi

latex - Pandas 数据框作为 latex 或 html 表 nbconvert

转载 作者:行者123 更新时间:2023-12-04 13:32:27 25 4
gpt4 key购买 nike

使用 nbconvert to latex & PDF 时,是否可以从 ipython notebook 中的 Pandas 数据框中获取格式良好的表格?

默认值似乎只是一个看起来很粗糙的字体左​​对齐的数字块。

我想要更像笔记本中数据框的 html 显示或 latex 表的东西。保存和显示 HTML 渲染数据帧的 .png 图像也可以,但事实证明如何做到这一点是难以捉摸的。

至少,我只想要一个简单的中心对齐的漂亮字体的表格。

我对使用 .to_latex() 方法从笔记本中或 nbconvert 输出中从 Pandas 数据帧获取 latex 表的各种尝试都没有任何运气。我还尝试过(在阅读 ipython 开发列表讨论并遵循自定义显示逻辑笔记本示例之后)使用 _repr_html_ 和 _repr_latex_ 方法制作自定义类,分别返回 _to_html() 和 _to_latex() 的结果。我认为 nb 转换的一个主要问题是 pdflatex 对数据帧 to_latex() 输出中的 {'s 或//'s 不满意。但是我不想在检查我没有错过任何东西之前开始摆弄它。

谢谢。

最佳答案

在此 Github issue 中讨论了一种更简单的方法。 .基本上,你必须添加一个 _repr_latex_ DataFrame 类的方法,该过程是 documented from pandas in their official documentation .

我在这样的笔记本中做到了这一点:

import pandas as pd

pd.set_option('display.notebook_repr_html', True)

def _repr_latex_(self):
return "\centering{%s}" % self.to_latex()

pd.DataFrame._repr_latex_ = _repr_latex_ # monkey patch pandas DataFrame

以下代码:
d = {'one' : [1., 2., 3., 4.],
'two' : [4., 3., 2., 1.]}
df = pd.DataFrame(d)
df

如果在笔记本中进行实时评估,则会转换为 HTML 表格,并转换为 PDF 格式的(居中)表格:
$ ipython nbconvert --to latex --post PDF notebook.ipynb

关于latex - Pandas 数据框作为 latex 或 html 表 nbconvert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20685635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com