将pandas中的输出数据格式化为

2024-04-25 17:01:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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

如何解决这个问题?


Tags: 文件to数据方法falsetrueformatpandas
1条回答
网友
1楼 · 发布于 2024-04-25 17:01:45

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

相关问题 更多 >

    热门问题