将pandas表导出为pdf

时间:2017-10-12 22:41:06

标签: python pandas pdf

我发现将用pandas here生成的表格导出为PDF的方法非常好,关于将其转换为png文件的部分对我来说无趣。

问题是,我收到以下错误消息:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-9818a71c26bb> in <module>()
     13 
     14 with open(filename, 'wb') as f:
---> 15     f.write(template.format(z.to_latex()))
     16 
     17 subprocess.call(['pdflatex', filename])

TypeError: a bytes-like object is required, not 'str'

我没有真正理解代码,这使得纠正错误变得非常困难。我的代码如下所示:

import subprocess

filename = 'out.tex'
pdffile = 'out.pdf'

template = r'''\documentclass[preview]{{standalone}}
\usepackage{{booktabs}}
\begin{{document}}
{}
\end{{document}}
'''

with open(filename, 'wb') as f:
    f.write(template.format(z.to_latex()))

subprocess.call(['pdflatex', filename])

其中z是使用DataFrame生成的pandas

希望有人可以提供帮助。 先感谢您, SITO。

1 个答案:

答案 0 :(得分:0)

问题是您要打开文件以字节模式写入 - 这是&#34; b&#34; character表示调用open() - 然后传递字符串数据。改变这个:

with open(filename, 'wb') as f:
    f.write(template.format(z.to_latex()))

到此:

with open(filename, 'w') as f:
    f.write(template.format(z.to_latex()))