保存“Out []”大 pandas 数据框表作为图 [英] Save the "Out[]" table of a pandas dataframe as a figure

查看:217
本文介绍了保存“Out []”大 pandas 数据框表作为图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个无用的功能,但对我来说非常有帮助。我想保存Canopy IDE中的输出。我不认为这是Canopy特有的,但为了清楚起见,这就是我使用的。例如,我的控制台Out [2]就是我想要的:

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 Canopy but for the sake of clarity that is what I use. For example, my console Out[2] is what I would want from this:

我认为格式化非常好并且每次重现这一点而不仅仅是保存输出将是一个浪费时间。所以我的问题是,我怎样才能掌握这个数字呢?理想情况下,implimentation将类似于标准方法,因此可以这样做:

I think that the formatting is quite nice and to reproduce this each time instead of just saving the output would be a waste of time. So my question is, how can I get a handle on this figure? Ideally the implimentation would be similar to standard methods, such that it could be done like this:

from matplotlib.backends.backend_pdf import PdfPages

pp = PdfPages('Output.pdf')
fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1)
df.plot(how='table')
pp.savefig()
pp.close()

注意:我意识到之前已经提出了一个非常类似的问题(如何将Pandas数据帧/系列数据保存为数字?)但它从未收到答案,我想我已经更清楚地说明了问题。

NOTE: I realize that a very similar question has been asked before ( How to save the Pandas dataframe/series data as a figure? ) but it never received an answer and I think I have stated the question more clearly.

推荐答案

这是一个有点hackish的解决方案,但它完成了工作。你想要一个.pdf,但你得到奖金.png。 :)

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 = "<!DOCTYPE html> <html> <body> <p> " + df.to_html() + " </p> </body> </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()

编辑欢迎。

这篇关于保存“Out []”大 pandas 数据框表作为图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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