pandas to_html no value representation

 ̄綄美尐妖づ 提交于 2021-02-07 08:32:29

问题


When I run the line below, the NaN number in the dataframe does not get modified. Utilizing the exact same argument with .to_csv(), I get the expected result. Does .to_html require something different?

df.to_html('file.html', float_format='{0:.2f}'.format, na_rep="NA_REP")


回答1:


It looks like the float_format doesn't play nice with na_rep. However, you can work around it if you pass a function to float_format that conditionally handles your NaNs along with the float formatting you want:

>>> df

  Group    Data
0     A  1.2225
1     A     NaN

Reproducing your problem:

>>> out = StringIO()
>>> df.to_html(out,na_rep="Ted",float_format='{0:.2f}'.format)
>>> out.getvalue()

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Group</th>
      <th>Data</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td> A</td>
      <td>1.22</td>
    </tr>
    <tr>
      <th>1</th>
      <td> A</td>
      <td> nan</td>
    </tr>
  </tbody>

So you get the proper float precision but not the correct na_rep. But the following seems to work:

>>> out = StringIO()
>>> fmt = lambda x: '{0:.2f}'.format(x) if pd.notnull(x) else 'Ted'
>>> df.to_html(out,float_format=fmt)
>>> out.getvalue()

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Group</th>
      <th>Data</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td> A</td>
      <td>1.22</td>
    </tr>
    <tr>
      <th>1</th>
      <td> A</td>
      <td> Ted</td>
    </tr>
  </tbody>
</table>


来源:https://stackoverflow.com/questions/23700835/pandas-to-html-no-value-representation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!