Save the “Out[]” table of a pandas dataframe as a figure

后端 未结 3 1388
南笙
南笙 2020-12-10 11:53

This may seem to be a useless feature but it would be very helpful for me. I would like to save the output I get inside Canopy IDE. I would not think this is specific to Can

3条回答
  •  被撕碎了的回忆
    2020-12-10 12:08

    Here is a somewhat hackish solution but it gets the job done. You wanted a .pdf but you get a bonus .png. :)

    import numpy as np
    import pandas as pd
    from matplotlib.backends.backend_pdf import PdfPages
    import matplotlib.pyplot as plt
    
    from PySide.QtGui import QImage
    from PySide.QtGui import QPainter
    from PySide.QtCore import QSize
    from PySide.QtWebKit import QWebPage
    
    arrays = [np.hstack([ ['one']*3, ['two']*3]), ['Dog', 'Bird', 'Cat']*2]
    columns = pd.MultiIndex.from_arrays(arrays, names=['foo', 'bar'])
    df =pd.DataFrame(np.zeros((3,6)),columns=columns,index=pd.date_range('20000103',periods=3))
    
    h = "   

    " + df.to_html() + "

    "; page = QWebPage() page.setViewportSize(QSize(5000,5000)) frame = page.mainFrame() frame.setHtml(h, "text/html") img = QImage(1000,700, QImage.Format(5)) painter = QPainter(img) frame.render(painter) painter.end() a = img.save("html.png") pp = PdfPages('html.pdf') fig = plt.figure(figsize=(8,6),dpi=1080) ax = fig.add_subplot(1, 1, 1) img2 = plt.imread("html.png") plt.axis('off') ax.imshow(img2) pp.savefig() pp.close()

    Edits welcome.

提交回复
热议问题