Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python有条件地将行样式格式应用于HTML表_Python_Html_Css - Fatal编程技术网

使用Python有条件地将行样式格式应用于HTML表

使用Python有条件地将行样式格式应用于HTML表,python,html,css,Python,Html,Css,我将数据框作为html表嵌入到电子邮件正文中。我想根据每个单元格中的值有条件地格式化单元格颜色和文本颜色 我首先从示例csv文件中读取一些数据,并使用pandasto_html()方法将其格式化为html表: df = pd.read_csv('example.csv') table = df.to_html() 现在,我为消息体创建了一些带有标记的基本html,并将表html代码插入消息体中的字符串中,如下所示: msg = """<html> <style

我将数据框作为html表嵌入到电子邮件正文中。我想根据每个单元格中的值有条件地格式化单元格颜色和文本颜色

我首先从示例csv文件中读取一些数据,并使用
pandas
to_html()
方法将其格式化为html表:

df = pd.read_csv('example.csv')
table = df.to_html()
现在,我为消息体创建了一些带有
标记的基本html,并将
html代码插入
消息体中的
字符串中,如下所示:

msg = """<html>
        <style type = "text/css">
            table, th, td { border: 1px solid black; }
        </style>
        <head></head>
        <body>
            <p>some text</p>
            <div> %s </div>
        </body
    </html>""" % (table)
现在,
result
是一个html字符串,带有一个具有类似

我将生成的html嵌入电子邮件中,其中包含:

msg_body = MIMEText(result, 'html')
msg.attach(msg_body)
这一切都很好

现在我需要根据每个单元格中的值有条件地格式化单元格颜色和字体颜色

我怎样才能做到最好? 正在考虑一些功能,例如:

def styleTable(x):
  if x < 0:
    return 'background-color: red'
  else
    return ''
def样式表(x):
如果x<0:
返回“背景色:红色”
其他的
返回“”
但是如何将其应用于html字符串?还是我需要在上游做些不同的事情


同样,这将被嵌入到电子邮件中,因此其中不能包含Javascript或CSS代码。感谢

随着pandas当前的发展,在将数据帧转换为HTML之前,有一个功能可以修改数据帧的
样式

简单的解决方案是定义一个函数,并将其作为参数传递给
style
apply
函数

以下是一个例子:

def f(val):
   # @params: val is the entire column if axis is 0
   # @returns: css style attributes based on the cell value
   return ['color: red' if x < 0 else 'color: blue' for x in val]

html_style = df.style.apply(f, axis = 0, subset = ['column_name']) # this will apply the css style to td of that column

 # above only returns Styler object so you need to convert it to string to render it
html_style.render() # this does the job
def(val):
#@params:val是轴为0时的整列
#@returns:基于单元格值的css样式属性
返回['color:red'如果x<0,则返回'color:blue'对于val中的x]
html_style=df.style.apply(f,axis=0,subset=['column_name'])#这将css样式应用于该列的td
#上面只返回Styler对象,所以您需要将其转换为字符串来呈现它
html_style.render()#这就可以了
您可以在此处阅读更多信息:

def f(val):
   # @params: val is the entire column if axis is 0
   # @returns: css style attributes based on the cell value
   return ['color: red' if x < 0 else 'color: blue' for x in val]

html_style = df.style.apply(f, axis = 0, subset = ['column_name']) # this will apply the css style to td of that column

 # above only returns Styler object so you need to convert it to string to render it
html_style.render() # this does the job