将Pandas数据框导出为表格图像 [英] Export a Pandas dataframe as a table image

查看:1005
本文介绍了将Pandas数据框导出为表格图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将Pandas数据框导出为图像文件? df.to_png()df.to_table().savefig('table.png')之类的东西.

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

此刻,我使用df.to_csv()导出数据帧.然后,我在Excel中打开该csv文件以使数据看起来很漂亮,然后将Excel表复制/粘贴为Powerpoint作为图像.我看到matplotlib有一个.table()方法,但是我无法使其与我的df一起使用.

At the moment I export a dataframe using df.to_csv(). I then open this csv file in Excel to make the data look pretty and then copy / paste the Excel table into Powerpoint as an image. I see matplotlib has a .table() method, but I'm having trouble getting it to work with my df.

我正在使用的数据帧有5列5行,每个单元格"都是一个数字.

The data frame I'm using has 5 columns and 5 rows and each 'cell' is a number.

推荐答案

使用一些其他代码,您甚至可以使输出看起来不错:

With some additional code, you can even make output look decent:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import six

df = pd.DataFrame()
df['date'] = ['2016-04-01', '2016-04-02', '2016-04-03']
df['calories'] = [2200, 2100, 1500]
df['sleep hours'] = [2200, 2100, 1500]
df['gym'] = [True, False, False]


def render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14,
                     header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
                     bbox=[0, 0, 1, 1], header_columns=0,
                     ax=None, **kwargs):
    if ax is None:
        size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])
        fig, ax = plt.subplots(figsize=size)
        ax.axis('off')

    mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)

    mpl_table.auto_set_font_size(False)
    mpl_table.set_fontsize(font_size)

    for k, cell in  six.iteritems(mpl_table._cells):
        cell.set_edgecolor(edge_color)
        if k[0] == 0 or k[1] < header_columns:
            cell.set_text_props(weight='bold', color='w')
            cell.set_facecolor(header_color)
        else:
            cell.set_facecolor(row_colors[k[0]%len(row_colors) ])
    return ax

render_mpl_table(df, header_columns=0, col_width=2.0)

这篇关于将Pandas数据框导出为表格图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆