How to set cell alignment in pandas dataframe.to_html()

X.X picture X.X · Oct 22, 2016 · Viewed 19k times · Source

The official document provided options to set cell alignment using to_html(justify='left/right') and it works. However, it is not clear how to justify non-header rows.

I've to use a hack to replace the HTML part

import pandas as pd
df = pd.DataFrame({'looooong_col':['1,234','234,567','3,456,789'],'short_col':[123,4,56]})
raw_html = df.to_html()
raw_html.replace('<tr>','<tr style="text-align: right;">')

So the modified html now is

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>looooong_col</th>
      <th>short_col</th>
    </tr>
  </thead>
  <tbody>
    <tr style="text-align: right;">
      <th>0</th>
      <td>1,234</td>
      <td>123</td>
    </tr>
    <tr style="text-align: right;">
      <th>1</th>
      <td>234,567</td>
      <td>4</td>
    </tr>
    <tr style="text-align: right;">
      <th>2</th>
      <td>3,456,789</td>
      <td>56</td>
    </tr>
  </tbody>
</table>

and it rendered ok in http://htmledit.squarefree.com/ but not when I write it out to a html file, the cells are still left-justified.

How to fix this?

Answer

ashishsingal picture ashishsingal · Jan 3, 2017

You can use the Styler functionality.

http://pandas.pydata.org/pandas-docs/stable/style.html

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(6,4),columns=list('ABCD'))
s = df.style.set_properties(**{'text-align': 'right'})
s.render()

s.render() returns a string of the generated CSS / HTML. Note the generated HTML will not be clean, as the internals declare a separate style for each cell.