[Tex/LaTex] how to print a data frame from pandas using pylatex

pylatexpython

I have a Pandas DataFrame Object.

I want to print it in a PDF file with pylatex. How should I do it?

Best Answer

(Note: I've never heard of pylatex before, so this answer is just based on looking at the example in the documentation.)

Depends on what you need, and how you want to print it. The simplest case would be to just print the values in the DataFrame as a matrix. Or you could just build a table.

The example below generates this:

enter image description here

import numpy as np
import pylatex as pl
import pandas as pd

df = pd.DataFrame({'a': [1,2,3], 'b': [9,8,7]})
df.index.name = 'x'

M = np.matrix(df.values)

doc = pl.Document()

with doc.create(pl.Section('Matrix')):
    doc.append(pl.Math(data=[pl.Matrix(M)]))

with doc.create(pl.Section('Table')):
    with doc.create(pl.Tabular('ccc')) as table:
        table.add_hline()
        table.add_row([df.index.name] + list(df.columns))
        table.add_hline()
        for row in df.index:
            table.add_row([row] + list(df.loc[row,:]))
        table.add_hline()


doc.generate_pdf('full', clean_tex=False)
Related Question