6

I have a Pandas DataFrame Object.

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

2 Answers 2

3

(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)
6

It might be noted, that pandas DataFrames already have a quite powerful to_latex method. Another approach that makes use of this method and does not reinvent the wheel would be:

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()

doc.packages.append(pl.Package('booktabs'))

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

# Difference to the other answer:
with doc.create(pl.Section('Table')):
    with doc.create(pl.Table(position='htbp')) as table:
        table.add_caption('Test')
        table.append(pl.Command('centering'))
        table.append(pl.NoEscape(df.to_latex(escape=False)))


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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.