用熊猫to_html格式化£符号



我正在尝试用to_html格式化DataFrame的输出,以便以 £ 作为前缀显示值。

df['gross'].map('£{0:,.0f}'.format)

返回:

尝试使用符号

df['gross'].map('£{0:,.0f}'.format)

返回:

尝试使用十六进制

我哪里出错了?

如果您只想将 £ 符号添加到 HTML 输出中,请不要更改数据帧本身 - 您将所有数值字段转换为字符串,并失去将它们视为数字的能力。to_html允许您指定如何使用参数formatters来设置事物的格式。

举个例子:

import pandas as pd
data = dict( index = ['A','B','C','D'], values = [1,2,3,4])
df = pd.DataFrame(data)
format_pounds = dict( values = '£{}'.format) # add £ to column 'values'
html = df.to_html(formatters = format_pounds)

我不知道你哪里出了问题,但你可以尝试使用样式器:

df = pd.DataFrame(data=[[1,2], [3.2, 4.01]], columns=['gross', 'fish'])
s = df.style
s.format({'gross': "£{0:,.0f}".format})
s.render()

生产:

<style  type="text/css" ></style>  <table id="T_97cbc3ba_cc03_11e8_8f0c_8c85905d0081" > <thead>    <tr>         <th class="blank level0" ></th>         <th class="col_heading level0 col0" >gross</th>        <th class="col_heading level0 col1" >fish</th>     </tr></thead> <tbody>    <tr>         <th id="T_97cbc3ba_cc03_11e8_8f0c_8c85905d0081level0_row0" class="row_heading level0 row0" >0</th>         <td id="T_97cbc3ba_cc03_11e8_8f0c_8c85905d0081row0_col0" class="data row0 col0" >£1</td>         <td id="T_97cbc3ba_cc03_11e8_8f0c_8c85905d0081row0_col1" class="data row0 col1" >2</td>     </tr>    <tr>         <th id="T_97cbc3ba_cc03_11e8_8f0c_8c85905d0081level0_row1" class="row_heading level0 row1" >1</th>         <td id="T_97cbc3ba_cc03_11e8_8f0c_8c85905d0081row1_col0" class="data row1 col0" >£3</td>         <td id="T_97cbc3ba_cc03_11e8_8f0c_8c85905d0081row1_col1" class="data row1 col1" >4.01</td>     </tr></tbody> </table>

最新更新