Edit table programmatically to fit content
<p>It's possible to create HTML page from a CSV file, with the following:</p>

<pre><code>import pandas as pd

df = pd.read_csv('../data.csv',delimiter=';', engine='python')
df.to_html('csv.html')
</code></pre>

<p>Column width of this table seems to respect the header (column title) size but for some columns content is larger then the column title and gets wrapped to next line. This happens with the following CSV, for the multi-word cells (<code>aaaaaaaaa aaaaaaaaa</code>): </p>

<pre><code>Name1;Name2;Name3;Name4;Name5
1;aaaaaaaaa aaaaaaaaa;b;aaaaaaaaa aaaaaaaaa;aaaaaaaaa aaaaaaaaa
2;aaaaaaaaa aaaaaaaaa;b;aaaaaaaaa aaaaaaaaa;aaaaaaaaa aaaaaaaaa
3;aaaaaaaaa aaaaaaaaa;b;aaaaaaaaa aaaaaaaaa;aaaaaaaaa aaaaaaaaa
</code></pre>

<p>I would like to make columns width large enough to fit content (avoid word wrap). How can I get there programmatically (using Python)?</p>

<p>Answer is based on <a href="http://stackoverflow.com/questions/39993959/edit-html-inserting-css-reference">this</a>.</p>

<pre><code>import pandas as pd

filename = 'csv.html'

df = pd.read_csv('../data.csv',delimiter=';', engine='python')

html_begin = '\
&lt;meta charset="UTF-8"&gt;\n\
&lt;html&gt;\n\
&lt;head&gt;&lt;link rel="stylesheet" type="text/css" href="csv.css"&gt;&lt;/head&gt;\n\
&lt;body&gt;\n\n'

html_end = '\n\
&lt;/body&gt;\n\
&lt;/html&gt;\n'

with open(filename, 'w') as f:   
    f.write(html_begin)
    df.to_html(f)
    f.write(html_end)
</code></pre>

<p>And <code>csv.css</code> is like:</p>

<pre><code>table {
    border: .5px solid lightgray;
    border-collapse: collapse;
    width: 100%;
}
th {
    border: .5px solid lightgray;
    text-align: center;
}
td {
    border: .5px solid lightgray;
    text-align: center;
    white-space:nowrap
}
</code></pre>

<p>Alternatively (a better alternative I'll say), one can avoid the CSS need and do everything via <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">Pandas Style</a> like:</p>

<pre><code>import pandas as pd

filename = 'csv_style.html'

df = pd.read_csv('../data.csv',delimiter=';', engine='python')

style =  df.style
style.set_properties(**{'text-align': 'center',
                       'white-space': 'nowrap'})

with open(filename, 'w') as f:  
    f.write(style.render())
</code></pre>

python html css python-2.7 pandas