Python 保存“文件”;Out[]”;数据框的表格(如图所示)
这似乎是一个无用的功能,但它会对我很有帮助。我想保存我在IDE中得到的输出。我不认为这是特定于天篷,但为了清楚起见,这是我使用的。例如,我的console Out[2]就是我想要的: 我认为格式很好,每次都要复制,而不仅仅是保存输出将是浪费时间。所以我的问题是,我怎样才能掌握这个数字?理想情况下,安装应类似于标准方法,因此可以这样进行:Python 保存“文件”;Out[]”;数据框的表格(如图所示),python,matplotlib,pandas,ipython,canopy,Python,Matplotlib,Pandas,Ipython,Canopy,这似乎是一个无用的功能,但它会对我很有帮助。我想保存我在IDE中得到的输出。我不认为这是特定于天篷,但为了清楚起见,这是我使用的。例如,我的console Out[2]就是我想要的: 我认为格式很好,每次都要复制,而不仅仅是保存输出将是浪费时间。所以我的问题是,我怎样才能掌握这个数字?理想情况下,安装应类似于标准方法,因此可以这样进行: from matplotlib.backends.backend_pdf import PdfPages pp = PdfPages('Output.pdf
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()
注意:我意识到以前有人问过一个非常类似的问题(),但它从未得到回答,我想我已经把这个问题说得更清楚了。我相信,您的IDE正在呈现一个HTML表。这就是ipython笔记本的功能 你可以这样处理它:
from IPython.display import HTML
import pandas as pd
data = pd.DataFrame({'spam':['ham','green','five',0,'kitties'],
'eggs':[0,1,2,3,4]})
h = HTML(data.to_html())
h
并保存到HTML文件:
my_file = open('some_file.html', 'w')
my_file.write(h.data)
my_file.close()
这是一个有点粗俗的解决方案,但它完成了任务。你想要一个.pdf,但你得到了一个奖金。png.:)
将numpy导入为np
作为pd进口熊猫
从matplotlib.backends.backend\u pdf导入PdfPages
将matplotlib.pyplot作为plt导入
从PySide.QtGui导入QImage
从PySide.QtGui导入QPainter
从PySide.QtCore导入QSize
从PySide.QtWebKit导入QWebPage
数组=[np.hstack(['one']*3,['two']*3]),['Dog','Bird','Cat']*2]
columns=pd.MultiIndex.from_数组(数组,名称=['foo','bar'])
df=pd.DataFrame(np.zeros((3,6)),columns=columns,index=pd.date\u range('20000103',periods=3))
h=“”+df.to_html()+””;
page=QWebPage()
第页setViewportSize(QSize(50005000))
frame=page.mainFrame()
frame.setHtml(h,“text/html”)
img=QImage(1000700,QImage.Format(5))
油漆工=油漆工(img)
帧渲染(画师)
(完)
a=img.save(“html.png”)
pp=PdfPages('html.pdf')
图=plt.图(图尺寸=(8,6),dpi=1080)
ax=图添加子批次(1,1,1)
img2=plt.imread(“html.png”)
打印轴(“关闭”)
ax.imshow(img2)
pp.savefig()
pp.close()
欢迎编辑。我认为这里需要的是在输出到pdf的图形中以一致的方式将表格输出到pdf文件 我的第一个想法是不使用matplotlib后端,即
from matplotlib.backends.backend_pdf import PdfPages
因为它似乎在格式化选项上有点限制,倾向于将表格格式化为图像(从而以不可选择的格式呈现表格文本)
如果希望在pdf中混合使用dataframe输出和matplotlib绘图,而不使用matplotlib pdf后端,我可以想到两种方法
首先,安装
xhtml2pdf
库。这似乎得到了一些零碎的支持,但确实存在一些问题。您可以通过pip
安装它,即pip安装xhtml2pdf
完成后,下面是一个简单的示例,先嵌入matplotlib图形,然后嵌入表格(所有文本均可选择),然后嵌入另一个图形。您可以使用CSS等更改格式以符合您的具体规格,但我认为这满足了简要要求:
from xhtml2pdf import pisa # this is the module that will do the work
import numpy as np
import pandas as pd
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
# Utility function
def convertHtmlToPdf(sourceHtml, outputFilename):
# open output file for writing (truncated binary)
resultFile = open(outputFilename, "w+b")
# convert HTML to PDF
pisaStatus = pisa.CreatePDF(
sourceHtml, # the HTML to convert
dest=resultFile, # file handle to recieve result
path='.') # this path is needed so relative paths for
# temporary image sources work
# close output file
resultFile.close() # close output file
# return True on success and False on errors
return pisaStatus.err
# Main program
if __name__=='__main__':
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))
# Define your data
sourceHtml = '<html><head>'
# add some table CSS in head
sourceHtml += '''<style>
table, td, th {
border-style: double;
border-width: 3px;
}
td,th {
padding: 5px;
}
</style>'''
sourceHtml += '</head><body>'
#Add a matplotlib figure(s)
plt.plot(range(20))
plt.savefig('tmp1.jpg')
sourceHtml += '\n<p><img src="tmp1.jpg"></p>'
# Add the dataframe
sourceHtml += '\n<p>' + df.to_html() + '</p>'
#Add another matplotlib figure(s)
plt.plot(range(70,100))
plt.savefig('tmp2.jpg')
sourceHtml += '\n<p><img src="tmp2.jpg"></p>'
sourceHtml += '</body></html>'
outputFilename = 'test.pdf'
convertHtmlToPdf(sourceHtml, outputFilename)
很好,这让我半途而废,但我没有HTML的经验。我想把HTML对象放入pdf文件中,我也在保存我的绘图。在我的原始问题中有一个玩具的例子。正如你所说的“那么我的问题是,我如何处理这个数字?”这就是我的回答。表格是否需要另存为.pdf格式?我已经更新了答案,将html对象保存到文件中。@user262536我不知道如何将html转换成.pdf格式。这个问题可能会有帮助:()。另一种方法可能是
pandas.DataFrame.to_latex()
方法,并使用pdflatex或类似工具与图形一起编译。不过我也从未尝试过这样做。对不起,我的意思是如何获得matplotlib类的句柄。例如,如何使该表的输出与matplotlib.pyplot.imread或matplotlib.pyplot.plot返回的输出类似。我应该更清楚。如果你愿意重新开始,那么DataFrame.tohtml()
的输出会有什么问题,它允许你使用一些相当标准的html分析,比如Beautiful Soup,来刮取单元格内容?你想要一个如何回答的答案吗?你说你想访问单元格内容,但你也说你想要一个PDF。这两个要求似乎有冲突,我对你想要什么样的赏金有点困惑,我不想仅仅给出一个不会让你更接近的答案。显然,您知道到_html
(以及到_latex
的选项,只要您提供链接,数据帧
。那还不能给你什么?可以将latex嵌入matplotlib绘图中。你想知道如何将HTML嵌入到pdf中吗?@Keith我猜了一下你可能想做什么,并添加了一个答案-让我知道它是否符合你的要求。它以不同的方式解决问题,不使用matplotlib的pdf后端作为pdf渲染解决方案。谢谢,这让我走得更远。上面的图像选项获取格式但没有选择,这将获取选择但没有格式。我会给你奖金,但我会试试看是否能得到一个更合理的格式。当然,谢谢。现在我知道这是您想要的,我将考虑引入一些CSS来设置表的样式,文档暗示这是可能的。加入一些CSS-不幸的是,它似乎忽略了边框样式:double
指令,但是边框宽度和填充似乎得到了尊重,并使布局更加美观。如果你真的需要一个特定的布局,我相信CSS可以做更多的事情。我不认为我需要一个特定的布局,I j
from xhtml2pdf import pisa # this is the module that will do the work
import numpy as np
import pandas as pd
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
# Utility function
def convertHtmlToPdf(sourceHtml, outputFilename):
# open output file for writing (truncated binary)
resultFile = open(outputFilename, "w+b")
# convert HTML to PDF
pisaStatus = pisa.CreatePDF(
sourceHtml, # the HTML to convert
dest=resultFile, # file handle to recieve result
path='.') # this path is needed so relative paths for
# temporary image sources work
# close output file
resultFile.close() # close output file
# return True on success and False on errors
return pisaStatus.err
# Main program
if __name__=='__main__':
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))
# Define your data
sourceHtml = '<html><head>'
# add some table CSS in head
sourceHtml += '''<style>
table, td, th {
border-style: double;
border-width: 3px;
}
td,th {
padding: 5px;
}
</style>'''
sourceHtml += '</head><body>'
#Add a matplotlib figure(s)
plt.plot(range(20))
plt.savefig('tmp1.jpg')
sourceHtml += '\n<p><img src="tmp1.jpg"></p>'
# Add the dataframe
sourceHtml += '\n<p>' + df.to_html() + '</p>'
#Add another matplotlib figure(s)
plt.plot(range(70,100))
plt.savefig('tmp2.jpg')
sourceHtml += '\n<p><img src="tmp2.jpg"></p>'
sourceHtml += '</body></html>'
outputFilename = 'test.pdf'
convertHtmlToPdf(sourceHtml, outputFilename)
import numpy as np
import pandas as pd
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
# Main program
if __name__=='__main__':
pp = PdfPages('Output.pdf')
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))
plt.plot(range(20))
pp.savefig()
plt.close()
# Calculate some sizes for formatting - constants are arbitrary - play around
nrows, ncols = len(df)+1, len(df.columns) + 10
hcell, wcell = 0.3, 1.
hpad, wpad = 0, 0
#put the table on a correctly sized figure
fig=plt.figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad))
plt.gca().axis('off')
matplotlib_tab = pd.tools.plotting.table(plt.gca(),df, loc='center')
pp.savefig()
plt.close()
#Add another matplotlib figure(s)
plt.plot(range(70,100))
pp.savefig()
plt.close()
pp.close()