pandas to_html 无值表示

5 投票
1 回答
2438 浏览
提问于 2025-04-18 06:47

当我运行下面这一行代码时,数据表中的NaN(不是一个数字)并没有被修改。而使用完全相同的参数调用.to_csv()时,我得到了预期的结果。难道.to_html需要什么不同的设置吗?

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

1 个回答

5

看起来 float_formatna_rep 之间不太兼容。不过,你可以通过给 float_format 传递一个函数来解决这个问题,这个函数可以根据情况处理你的 NaN(缺失值),同时还可以格式化你想要的浮点数:

>>> df

  Group    Data
0     A  1.2225
1     A     NaN

重现你的问题:

>>> 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>

这样你就能得到正确的小数精度,但 na_rep 却不对。不过,下面的代码似乎可以解决这个问题:

>>> 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>

撰写回答