導(dǎo)出excel顯示顏色

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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容