在 Pandas to_html 中格式化输出数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14899818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:39:04  来源:igfitidea点击:

format output data in pandas to_html

pythonpandas

提问by wuwucat

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:

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

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?

如何解决这个问题呢?

回答by DSM

From the to_htmldocs:

to_html文档:

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