format output data in pandas to_html

From the to_html docs:

float_format : one-parameter function, optional
    formatter function to apply to columns' elements if they are floats
    default None

You need to pass a function. For example:

>>> df = pd.DataFrame({"A": [1.0/3]})
>>> df
          A
0  0.333333

>>> print df.to_html()
<table border="1" class="dataframe">
    <tr>
      <th>0</th>
      <td> 0.333333</td>
    </tr>
[...]

but

>>> print df.to_html(float_format=lambda x: '%10.2f' % x)
<table border="1" class="dataframe">
[...]
    <tr>
      <th>0</th>
      <td>      0.33</td>
    </tr>
[...]

Without a lambda, you can pass a str.format function directly:

df = pd.DataFrame(...)
df.to_html(float_format='{:10.2f}'.format)

Tags:

Python

Pandas