首页 > 解决方案 > pandas 到带有格式的 html

问题描述

我有一个项目,我正在从熊猫数据框创建多个 html 表。

目前我有一个熊猫数据框,其中包含浮点数、字符串和布尔值的组合:

import pandas as pd

df = pd.DataFrame()

df['text1'] = ['G90T0','G90T180','G90T0RL CD1','G90T180LL CD1','G90T0RL CD2','G90T180 CD2']
df['text2'] = ['value1','value1','value2','value3','value1','value1']
df['floats1'] = [90.0, 90.0, 90.0, 90.0, 90.0, 90.0]
df['bools1'] = [True, True, True, True, False, True]
df['bools2'] = [True, False, True, True, True, True]
df['floats1'] = [90.0, 90.0, 90.0, 90.0, 90.0, 90.0]
df['floats2'] = [5.2, 4.9, 4, 6, 4.1, 3]

html = df.to_html()
path = "C:\\path"
text_file = open('test.html', "w")
text_file.write(html)
text_file.close()

我正在尝试编写一个格式化函数,根据多种不同的条件突出显示红色或绿色的单元格颜色。以下是为这个特定数据框着色的规则:

列'text2':如果不等于'value1',则为红色

'boolS1' 和 'boolS2' 列:True 为绿色,False 为红色

列'floats2':如果大于5,则为红色,如果等于或小于5,则为绿色

其他列:无格式。

输出应如下所示: 在此处输入图像描述

标签: pythonhtmlpandas

解决方案


推荐阅读