我有熊猫数据帧,我正在尝试通过首先将其转换为html来将其转换为pdf
。在将其转换为html时,我们使用col_space属性来帮助设置html表中所有列的列宽。
some_dataframe.to_html(os.path.abspath(html_output_file_path), index=False, border=1, col_space=100)
但我的要求是,我只需要增加特定列的宽度,而不是增加最终pdf
中出现的所有列的宽度。有没有办法只增加一列的宽度?
发布于 2019-10-16 20:10:23
您可以利用HTML,它提供了对生成的.style外观的高粒度控制。不过,还需要一些CSS知识:
import pandas as pd
import numpy as np
import pdfkit
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1)
styles = [dict(selector='.col3', props=[('min-width', '300px')]), dict(selector='.data', props=[('min-width', '6em')])]
html = df.style.hide_index().set_table_styles(styles).set_table_attributes('border=3 cellspacing=0').render()
with open(os.path.abspath(html_output_file_path), 'w') as f:
f.write(html)
pdfkit.from_string(html, os.path.abspath(pdf_output_file_path))
这将生成以下外观:
发布于 2019-10-16 20:47:34
这就是你可以做的
df = pd.DataFrame({'test': ['foo foo foo foo foo foo foo foo', 'bar bar bar bar bar'],
'number': [1, 2]})
df.style.set_properties(subset=['test'], **{'width': '300px'})
new_df=df.style.set_properties(subset=['testt'], **{'width': '300px'})
渲染此文件并保存到文件
html_df = new_df.hide_index().render()
with open("new_df.html","w") as fp:
fp.write(html_df)
从现在开始,Pdfkit或任何类似的库都应该能起作用。
https://stackoverflow.com/questions/58335791
复制相似问题