如何在转换为html时向特定的dataframe列添加背景色

问题描述

需要对列色使用不同的颜色。使用下面的代码,但不能直接在邮件获取数据。 To html方法可以正常工作以生成表,但需要对Dataframe中的所有列进行比较颜色。

pdf.style.apply(highlight_cols,axis=None)

还有一个

output=df.to_html() 
batch_name=['a','a','p','o'] 
duration=['10','45','65','20'] 
batch_dict={'Batch Name': batch_name,'Duration':duration} 
pdf = pd.DataFrame(batch_dict) 
def highlight_cols(x): 
    pdf = x.copy()   
    pdf[['Batch Name']] = 'background-color: grey'     
    print('pdf x',pdf)    
    return pdf    

解决方法

def highlight_col(x): if x.name in 'B'return ['background-color: #feffc1']*x.shape[0] elif x.name in 'Duration':e return ['background-color: #ff9090']*x.shape[0] elsereturn ['background-color: None']*x.shape[0]

pdf = pdf.style.apply(highlight_col,axis = 0).hide_index()。set_table_styles(styles).set_caption('Check')