def my_style(i):
ret = []
for index,v in enumerate(i):
if v>0.1 and i.name in ['A','B',"C"] and list(i.index)[index] in ['a','b','c']:
# i是每一列,列表的形式, v是i中的每个元素,i.name是列名,list(i.index)[index] 是行索引
ret.append('background-color:yellow') # 设置背景色
else:
ret.append('')
for index,v in enumerate(i):
if v > 0.2 and v<0.5:
ret[index]+=";color:red" # 设置字体颜色
else:
ret[index]+=";color:blue"
return ret
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A':np.linspace(1,10,10)})
df = pd.concat([df,pd.DataFrame(np.random.randn(10,4),columns=list('BCDE'))],axis=1)
df.index = ['a','b','c','d','e','f','g','h',"l",'m'] #重新设置索引
df = df.style.apply(my_style) # 应用样式,只能应用一次
df.to_excel('样式标色.xlsx')
df.render() # 将df以html代码的形式显示
image.png