Pandas style function to highlight specific columns

前端 未结 2 1877
萌比男神i
萌比男神i 2020-11-28 10:55

I have been trying to write a function to use with pandas style. I want to highlight columns that I specify in the arguments. This is not very elegant, but, for example:

2条回答
  •  再見小時候
    2020-11-28 11:21

    You can do it bit more dynamically:

    data =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
    
    # dictionary of column colors
    coldict = {'A':'grey', 'C':'yellow'}
    
    def highlight_cols(s, coldict):
        if s.name in coldict.keys():
            return ['background-color: {}'.format(coldict[s.name])] * len(s)
        return [''] * len(s)
    
    data.style.apply(highlight_cols, coldict=coldict)
    

提交回复
热议问题