pandas dataframe为latex或html table nbconvert [英] pandas dataframe as latex or html table nbconvert

查看:145
本文介绍了pandas dataframe为latex或html table nbconvert的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用nbconvert to latex& amp;是否有可能从ipython笔记本中的pandas数据框中获取格式良好的表格。 PDF?

Is it possible to get a nicely formatted table from a pandas dataframe in ipython notebook when using nbconvert to latex & PDF?

默认似乎只是一个左对齐的数字块,看起来很伪劣。

The default seems to be just a left-aligned block of numbers in a shoddy looking font.

我想更像是笔记本中的数据帧的html显示或乳胶表。保存和显示HTML渲染数据帧的.png图像也没问题,但究竟如何做到这一点已经证明是难以捉摸的。

I would like to have something more like the html display of dataframes in the notebook, or a latex table. Saving and displaying a .png image of an HTML rendered dataframe would also be fine, but how exactly to do that has proved elusive.

最低限度,我只想要一个简单的中心对齐表格。

Minimally, I would just like a simple centre-aligned table in a nice font.

我没有幸运尝试使用.to_latex()方法从pandas数据帧获取乳胶表,无论是在笔记本中还是在nbconvert输出中。我也尝试过(在阅读ipython开发列表讨论之后,并按照自定义显示逻辑笔记本示例)使用_repr_html_和_repr_latex_方法创建自定义类,分别返回_to_html()和_to_latex()的结果。我认为nb转换的一个主要问题是pdflatex对数据帧to_latex()输出中的{'或//'不满意。但是我不想在检查之前开始摆弄那个我没有错过的东西。

I haven't had any luck with various attempts to use the .to_latex() method to get latex tables from pandas dataframes, either within the notebook or in nbconvert outputs. I've also tried (after reading ipython dev list discussions, and following the custom display logic notebook example) making a custom class with _repr_html_ and _repr_latex_ methods, returning the results of _to_html() and _to_latex(), respectively. I think a main problem with the nb conversion is that pdflatex isn't happy with either the {'s or the //'s in the dataframe to_latex() output. But I don't want to start fiddling around with that before checking I haven't missed something.

谢谢。

推荐答案

Github问题。基本上,您必须向DataFrame类添加 _repr_latex _ 方法,该过程是

There is a simpler approach that is discussed in this Github issue. Basically, you have to add a _repr_latex_ method to the DataFrame class, a procedure that is documented from pandas in their official documentation.

我这样做了像这样的笔记本:

I did this in a notebook like this:

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格式的(居中)表格:

turns into an HTML table if evaluated live in the notebook, and it converts into a (centered) table in PDF format:

$ ipython nbconvert --to latex --post PDF notebook.ipynb

这篇关于pandas dataframe为latex或html table nbconvert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆