格式化pandas to_html中的输出数据

时间:2013-02-15 17:11:13

标签: python pandas

我使用pandas'to_html生成输出文件,当数据写入文件时,它们在小数点后面有很多位数。 pandas的to_html float_format方法可以限制数字,但是当我使用'float_format'时如下:

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

它引发了一个例外:

typeError: 'str' object is not callable

如何解决这个问题?

2 个答案:

答案 0 :(得分:11)

来自to_html文档:

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

您需要传递一个功能。例如:

>>> 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>
[...]

>>> 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>
[...]

答案 1 :(得分:1)

如果没有lambda,则可以直接传递str.format函数:

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