在pandas中格式化输出数据为HTML

16 投票
2 回答
21066 浏览
提问于 2025-04-17 16:01

我在使用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 个回答

9

如果不使用 lambda,你可以直接传递一个 str.format 函数:

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

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

撰写回答