根据条件向列名和单元格添加背景色

时间:2018-11-05 22:04:27

标签: python html pandas dataframe pandas-styles

是否可以在为列名添加背景色的同时还根据单独的条件更改单元格背景色?

我目前能够根据条件突出显示单元格,但不确定如何为列名添加背景色:

# create dataframe 
import pandas as pd

data = {'Cuisine':['Italian','Indian','Nepalese','Mexican', 'Thai'],
   'Geographic Location':['Europe','Asia','Asia','N.America','Asia']}

df = pd.DataFrame(data) print(df)

    Cuisine Geographic Location
0   Italian              Europe
1    Indian                Asia
2  Nepalese                Asia
3   Mexican           N.America
4      Thai                Asia


# highlight cells based on condition
def highlight_Asia(x):
    return ['background-color: GreenYellow' if v =='Asia' else '' for v in x]

df.style.apply(highlight_Asia)

cells highlighted based on cond.

# highlight column names
def highlight_header(x):
    y= ['background-color: LightSkyBlue' for v in list(x)]
    return y

df.style.apply(highlight_header)

cant figure out how to highlight column names

所需结果:

desired outcome

参考: 1 2

0 个答案:

没有答案