Export a Pandas dataframe as a table image

前端 未结 4 976
独厮守ぢ
独厮守ぢ 2020-11-27 02:55

Is it possible to export a Pandas dataframe as an image file? Something like df.to_png() or df.to_table().savefig(\'table.png\').

At the mo

4条回答
  •  粉色の甜心
    2020-11-27 03:09

    If you have pdflatex and imagemagick installed, you could export the DataFrame to tex, use pdflatex to convert it to a pdf file, and then convert the pdf to png using imagemagick:

    import pandas as pd
    import numpy as np
    import subprocess
    
    df = pd.DataFrame({'d': [1., 1., 1., 2., 2., 2.],
                       'c': np.tile(['a', 'b', 'c'], 2),
                       'v': np.arange(1., 7.)})
    filename = 'out.tex'
    pdffile = 'out.pdf'
    outname = 'out.png'
    
    template = r'''\documentclass[preview]{{standalone}}
    \usepackage{{booktabs}}
    \begin{{document}}
    {}
    \end{{document}}
    '''
    
    with open(filename, 'wb') as f:
        f.write(template.format(df.to_latex()))
    
    subprocess.call(['pdflatex', filename])
    subprocess.call(['convert', '-density', '300', pdffile, '-quality', '90', outname])
    

    enter image description here

    If you install phantomjs and imagemagick, you could export the DataFrame to HTML and then use phantomjs to convert the HTML to png, and imagemagick to crop the result:

    import pandas as pd
    import numpy as np
    import subprocess
    
    df = pd.DataFrame({'d': [1., 1., 1., 2., 2., 2.],
                       'c': np.tile(['a', 'b', 'c'], 2),
                       'v': np.arange(1., 7.)})
    filename = '/tmp/out.html'
    outname = '/tmp/out.png'
    cropname = '/tmp/cropped.png'
    
    with open(filename, 'wb') as f:
        f.write(df.to_html())
    rasterize = '/path/to/phantomjs/examples/rasterize.js'
    subprocess.call(['phantomjs', rasterize, filename, outname])
    subprocess.call(['convert', outname, '-trim', cropname])
    

    enter image description here

提交回复
热议问题