16

I use pandas' to_html to generate output file, when data are written to the file they have many digits after the decimal point. The pandas' to_html float_format method can limit the digits, but when I used 'float_format' as below:

DataFormat.to_html(header=True,index=False,na_rep='NaN',float_format='%10.2f')

it raise a exception:

typeError: 'str' object is not callable

how to solve this problem?

2 Answers 2

21

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>
[...]
Sign up to request clarification or add additional context in comments.

Comments

9

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.