Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase width of a specific column while converting pandas Dataframes to PDF

I have pandas dataframes that I am trying to convert into a pdf by first converting it to html. While converting it to html, we have col_space property that helps set column width for all columns of the html table.

some_dataframe.to_html(os.path.abspath(html_output_file_path), index=False, border=1, col_space=100)

But my requirement is that I need to increase the width of a specific column only and not all columns present in the final pdf. Is there a way that I can increase the width of a single column only?

like image 886
Shashank Shekher Avatar asked Oct 11 '19 06:10

Shashank Shekher


People also ask

How do you adjust column width in python?

Setting the Column Width Set the width of a column by calling the Cells collection's setColumnWidth method. The setColumnWidth method takes the following parameters: Column index, the index of the column that you're changing the width of. Column width, the desired column width.

How do you set a fixed td width?

By using CSS, the styling of HTML elements is easy to modify. To fix the width of td tag the nth-child CSS is used to set the property of specific columns(determined by the value of n) in each row of the table.


2 Answers

You can exploit .style properety, which provides high grain control over the looks of the resulting HTML. Some CSS knowledge is required, though:

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))

This will generate the following look: enter image description here

like image 86
igrinis Avatar answered Sep 29 '22 06:09

igrinis


This is how you can do it

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'})

Render this and save to file

html_df = new_df.hide_index().render()
with open("new_df.html","w") as fp:
    fp.write(html_df)

Pdfkit or any similar library should do trick from now on

like image 30
nithin Avatar answered Sep 29 '22 06:09

nithin