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中的每個(gè)元素,i.name是列名,list(i.index)[index] 是行索引
ret.append('background-color:yellow') # 設(shè)置背景色
else:
ret.append('')
for index,v in enumerate(i):
if v > 0.2 and v<0.5:
ret[index]+=";color:red" # 設(shè)置字體顏色
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'] #重新設(shè)置索引
df = df.style.apply(my_style) # 應(yīng)用樣式,只能應(yīng)用一次
df.to_excel('樣式標(biāo)色.xlsx')
df.render() # 將df以html代碼的形式顯示
image.png