格式化pandas to_html中的输出数据

wuw*_*cat 8 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')
Run Code Online (Sandbox Code Playgroud)

它引发了一个例外:

typeError: 'str' object is not callable
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题呢?

DSM*_*DSM 12

来自to_html文档:

float_format : one-parameter function, optional
    formatter function to apply to columns' elements if they are floats
    default None
Run Code Online (Sandbox Code Playgroud)

你需要传递一个功能.例如:

>>> 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>
[...]
Run Code Online (Sandbox Code Playgroud)

>>> 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>
[...]
Run Code Online (Sandbox Code Playgroud)


Ser*_*tch 9

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

df = pd.DataFrame(...)
df.to_html(float_format='{:10.2f}'.format)
Run Code Online (Sandbox Code Playgroud)