【问题标题】:Python: Pandas how to highlight the Header RowPython:Pandas 如何突出显示标题行
【发布时间】:2021-01-28 05:39:01
【问题描述】:

这是突出显示表中所有行的函数:

def highlight(s): 
if s.Points == 10 or s.Points == 15:
    return ['background-color : #d9ead3']*3
elif s.Points == 8 or s.Points == 6:
    return ['background-color : #cfe2f3']*3
elif s.Points == 5:
    return ['background-color : #f4cccc']*3
elif s.Points == 4:
    return ['background-color : #fff2cc']*3
elif s.Points == 3:
    return ['background-color : #d9d2e9']*3
elif s.Points == 2:
    return ['background-color : #c9daf8']*3
elif s.Points == 1:
    return ['background-color : #ead1dc']*3
else:
    return ['background-color : white']*3

然后我像这样调用该函数:

dfnew = df.style.apply(highlight, axis = 1).set_table_styles([{'selector' : '', 
                        'props' : [('border', 
                                    '2px solid black')]}]).set_properties(**{'font-size':'11pt'}) 

我还想突出显示标题行(Rank、GolferName、Points)。我该怎么做?

这是我的桌子的样子:

【问题讨论】:

    标签: python pandas formatting highlight


    【解决方案1】:

    你试过了吗?

    col_loc_1 = df.columns.get_loc('Rank') + 2
    col_loc_1 = df.columns.get_loc('GolferName') + 2
    
    df.style.apply(highlight, axis = 1).set_table_styles(
         [{'selector': f'th:nth-child({col_loc_1})',
           'props': [('background-color', '#ff0')]},
         {'selector': f'th:nth-child({col_loc_1})',
           'props': [('background-color', '#00F')]}])
    

    【讨论】:

      猜你喜欢
      • 2016-08-28
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多