pandas to_html 无值表示 [英] pandas to_html no value representation
问题描述
当我运行下面的行时,数据框中的 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 以及您想要的浮点格式,您可以解决这个问题:
重现您的问题:
<预><代码>>>>输出 = StringIO()>>>df.to_html(out,na_rep="Ted",float_format='{0:.2f}'.format)>>>out.getvalue()<table border="1" class="dataframe"><头><tr style="text-align: right;"><th></th><th>组</th><th>数据</th></tr></thead><tr>第 0 次<td></td><td>1.22</td></tr><tr>第 1 个<td></td><td>南</td></tr></tbody>所以你得到了正确的浮点精度,但不是正确的na_rep
.但以下似乎有效:
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")
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>
这篇关于pandas to_html 无值表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!