【问题标题】:Format £ sign with pandas to_html用 pandas to_html 格式化 £ 符号
【发布时间】:2019-03-14 16:06:40
【问题描述】:

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

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

返回:

Attempt with symbol

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

返回:

Attempt with hex

我哪里错了?

【问题讨论】:

    标签: python html pandas


    【解决方案1】:

    如果您只想在 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)
    

    【讨论】:

      【解决方案2】:

      我不知道你一定会出错,但你可以尝试使用样式器:

      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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-16
        • 2014-12-04
        • 2013-08-08
        • 2017-09-04
        相关资源
        最近更新 更多