python - pandas DataFrame.to_html 将 html 表中的负数更改为红色
问题描述
我有简单的 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>
有什么简单的方法,怎么做?非常感谢您的任何提示。
解决方案
在转换为 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>
推荐阅读
- c++ - 如何填充闰年的元素
- java - 为什么在要求用户输入字符时收到错误消息?
- javascript - 在jquery中将两个输入字段计算为具有多个表行的第三个输入字段
- java - Rest 方法:返回 XML 集合而不是正确分组
- protocol-buffers - “协议缓冲区”这个名称从何而来?
- c++ - tensorflow C++ 批量推理
- reactjs - 更新的页面没有在嵌套路由中使用“history.push”重新渲染
- swift - Swift Generics - 无法推断通用参数“T”
- python - Python 递归骑士之旅
- angularjs - 通过 angularjs 调用 Web API 返回奇怪的数据格式