Python Pandas 样式功能突出显示特定列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41654949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:22:24  来源:igfitidea点击:

Pandas style function to highlight specific columns

pythonpandasstyles

提问by Maria Petrova

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:

我一直在尝试编写一个用于熊猫风格的函数。我想突出显示我在参数中指定的列。这不是很优雅,但是,例如:

data =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))

def highlight_cols(df, cols, colcolor = 'gray'):
    for col in cols:
        for dfcol in df.columns:
            if col == cols:
                color = colcolor
    return ['background-color: %s' % color]*df.shape[0]

then call with:

然后调用:

data.style.apply(highlight_cols(cols=['B','C']))

I get an error: ("'Series' object has no attribute 'columns'")

我收到一个错误:(“'Series' 对象没有属性 'columns'”)

I think I fundamentally don't quite understand how the styler calls and applies the function.

我想我从根本上不太了解样式器如何调用和应用该函数。

Thanks,

谢谢,

回答by jezrael

I think you can use Slicing in Stylesfor select columns Band Cand then Styler.applymapfor elementwise styles.

我想你可以使用在切片Styles的选择列B,并CStyler.applymap为按元素的风格。

import pandas as pd
import numpy as np

data =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
#print (data)

def highlight_cols(s):
    color = 'grey'
    return 'background-color: %s' % color

data.style.applymap(highlight_cols, subset=pd.IndexSlice[:, ['B', 'C']])

pic

图片

If you want more colors or be more flexible, use Styler.apply(func, axis=None), the function must return a DataFramewith the same index and column labels:

如果您想要更多颜色或更灵活,请使用Styler.apply(func, axis=None),该函数必须返回DataFrame具有相同索引和列标签的 a:

import pandas as pd
import numpy as np

data =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
#print (data)

def highlight_cols(x):
    #copy df to new - original data are not changed
    df = x.copy()
    #select all values to default value - red color
    df.loc[:,:] = 'background-color: red'
    #overwrite values grey color
    df[['B','C']] = 'background-color: grey'
    #return color df
    return df    

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

pic1

图片1

回答by MaxU

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)

enter image description here

在此处输入图片说明