pandas dataframe as latex or html table nbconvert

后端 未结 3 1100
孤街浪徒
孤街浪徒 2020-12-28 10:39

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 le

3条回答
  •  难免孤独
    2020-12-28 11:18

    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
    

    The following code:

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

    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
    

提交回复
热议问题