Py
Hallo,
I also need to print some Pandas DataFrame for organizing reports as .pdf. I tried ReportLab directly with df and had an AttributeError: DataFrame object that does not have a split attribute. I tried with df.values () and had a "TypeError: numpy.ndarray object" not callable ".
When I closed the idea of creating a .pdf report, I tried str (df) and I had some result in .pdf :-) ... The code looks like this:
import pandas as pd from reportlab.pdfgen import canvas PATH_OUT = "C:\\" def pdf_df(c, testo, x, y): c.drawAlignedString(x,y, testo) df = pd.DataFrame({'a':[3,4,5], 'b':[6,7,6],'c':[9,10,11]}) print df, type(df) print'' df1 = (df['a'].groupby([df['b'], df['a']])).sum() print df1, type(df1) print '' c = canvas.Canvas(PATH_OUT + 'out.pdf') pdf_df (c, str(df), 300, 500) pdf_df (c, str(df1), 300, 480) c.showPage() c.save()
What do you think? Could this make sense, or could there be some “smarter” way?
It doesn't seem so spectacular, and I initially hoped to get from ReportLab. It seems that I would need to somehow wrap the lines .. and the sizes will change ...
Fabio
=====
Now I am much happier from the solution below, while I, too, was not satisfied with the above.
This is based on ReportLab networks, they work on lists. Thus, the code converts the DF to a list, which is then processed as a ReportLab grid :-)
Here he is:
from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import * from reportlab.lib import colors import pandas as pd import random PATH_OUT = "C:\\" elements = [] styles = getSampleStyleSheet() doc = SimpleDocTemplate(PATH_OUT + 'Report_File.pdf') elements.append(Paragraph("Report Title", styles['Title'])) data = [[random.random() for i in range(1,4)] for j in range (1,8)] df = pd.DataFrame (data) lista = [df.columns[:,].values.astype(str).tolist()] + df.values.tolist() ts = [('ALIGN', (1,1), (-1,-1), 'CENTER'), ('LINEABOVE', (0,0), (-1,0), 1, colors.purple), ('LINEBELOW', (0,0), (-1,0), 1, colors.purple), ('FONT', (0,0), (-1,0), 'Times-Bold'), ('LINEABOVE', (0,-1), (-1,-1), 1, colors.purple), ('LINEBELOW', (0,-1), (-1,-1), 0.5, colors.purple, 1, None, None, 4,1), ('LINEBELOW', (0,-1), (-1,-1), 1, colors.red), ('FONT', (0,-1), (-1,-1), 'Times-Bold'), ('BACKGROUND',(1,1),(-2,-2),colors.green), ('TEXTCOLOR',(0,0),(1,-1),colors.red)] table = Table(lista, style=ts) elements.append(table) doc.build(elements)
I am very interested to know about other possible solutions.
Bye, Fabio.