Dat*_*ede 5 python dataframe pandas
当我运行下面的行时,数据框中的 NaN 数字不会被修改。使用与 完全相同的参数.to_csv(),我得到了预期的结果。.to_html需要不同的东西吗?
df.to_html('file.html', float_format='{0:.2f}'.format, na_rep="NA_REP")
看起来 和float_format玩得不太好na_rep。float_format但是,如果您传递一个函数来有条件地处理 NaN 以及您想要的浮点格式,则可以解决这个问题:
>>> df
Group Data
0 A 1.2225
1 A NaN
Run Code Online (Sandbox Code Playgroud)
重现您的问题:
>>> 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>
Run Code Online (Sandbox Code Playgroud)
所以你得到了正确的浮点精度,但不是正确的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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2409 次 |
| 最近记录: |