11

pandas の to_html を使用して出力ファイルを生成します。データがファイルに書き込まれると、小数点以下の桁数が多くなります。パンダの 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

この問題を解決するには?

4

2 に答える 2

17

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>
[...]
于 2013-02-15T17:21:21.990 に答える