【问题标题】:pandas DataFrame.to_html change negative numbers in html table as redpandas DataFrame.to_html 将 html 表中的负数更改为红色
【发布时间】:2019-01-27 09:57:06
【问题描述】:

我有简单的 pandas DataFrame,我需要将其转换为像这样的 html 表

import pandas as pd
df = pd.DataFrame({
                'Col1': ['20180817','20180816'],
                'Col2': [3541, 2547],
                'Col3': [-254, 147],
                'Col4': ['-74.5%', '25.28%']
             })

df_html = df.to_html(index=False, col_space=500)

但还需要将所有负数的颜色改为红色,例如

<td>-74.5%</td>

有什么简单的方法,怎么做?非常感谢您的任何提示。

【问题讨论】:

  • 有一个简单的方法...pandas.pydata.org/pandas-docs/stable/style.html ...但这适用于数字而不是字符串...Col4是字符串
  • 您需要对所有列还是仅对Col4
  • 不仅适用于 Col4,而且适用于所有负号列。

标签: python python-3.x python-2.7 pandas


【解决方案1】:

在转换为 html 之前更新您的列:

df['Col4'] = df['Col4'].map(lambda x: f'<font color="red">{x}</font>' if x[0] == '-' else x)
df_html = df.to_html(index=False, col_space=500, escape=False)

结果:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th style="min-width: 500;">Col1</th>
      <th style="min-width: 500;">Col2</th>
      <th style="min-width: 500;">Col3</th>
      <th style="min-width: 500;">Col4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>20180817</td>
      <td>3541</td>
      <td>-254</td>
      <td><font color="red">-74.5%</font></td>
    </tr>
    <tr>
      <td>20180816</td>
      <td>2547</td>
      <td>147</td>
      <td>25.28%</td>
    </tr>
  </tbody>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-08
    • 2010-10-12
    • 2016-04-09
    • 1970-01-01
    • 2011-03-13
    • 2017-05-17
    • 2018-12-17
    • 1970-01-01
    相关资源
    最近更新 更多