Pandas样式函数为列值的匹配设置多个行属性

pdtvr36n  于 2023-04-28  发布在  其他
关注(0)|答案(1)|浏览(89)

对于pandas数据框中给定列中具有给定值的行,我无法弄清楚如何将这些行同时着色为黄色和粗体。
下面的代码成功地根据列值为行着色。或者它可以用于根据列值成功地粗体输入行。下面的代码基于this link by Stephen

import pandas as pd

df = pd.DataFrame({"A" : [14, 4, 5, 4, 1],
                   "B" : [5, 2, 54, 3, 2],
                   "C" : [20, 20, 7, 3, 8], 
                   "D" : [14, 3, 6, 2, 6],
                   "E" : [23, 45, 64, 32, 23]}) 

def highlight(s):
    if s.C == 7:
        return ['background-color: yellow'] * len(s)                             # this works
        # return ['font-weight: bold'] * len(s)                                    # this works
        # return [{'background-color: yellow' & 'font-weight: bold'}] * len(s)     # this fails
        # return [('background-color: yellow') & ('font-weight: bold')] * len(s)   # this fails
        # return [{('background-color: yellow') & ('font-weight: bold')}] * len(s) # this fails
    else:
        return ['background-color: white'] * len(s)

df.style.apply(highlight, axis=1)

Hopefully this is an image of the output
我不知道如何使df.C == 7的行既着色又加粗。

kq0g1dla

kq0g1dla1#

您可以这样做以获得所需的结果。
您可以使用分号同时包含颜色和字体:

return ['background-color: yellow; font-weight: bold'] * len(s)

完整代码在这里:

import pandas as pd

df = pd.DataFrame({"A" : [14, 4, 5, 4, 1],
                   "B" : [5, 2, 54, 3, 2],
                   "C" : [20, 20, 7, 3, 8], 
                   "D" : [14, 3, 6, 2, 6],
                   "E" : [23, 45, 64, 32, 23]}) 

def highlight(s):
    if s.C == 7:
        return ['background-color: yellow; font-weight: bold'] * len(s)  # this works
    else:
        return ['background-color: white'] * len(s)
    
df.style.apply(highlight, axis=1)

我删除了你使用的所有其他代码(不再需要):

# return ['font-weight: bold'] * len(s)                                    # this works
        # return [{'background-color: yellow' & 'font-weight: bold'}] * len(s)     # this fails
        # return [('background-color: yellow') & ('font-weight: bold')] * len(s)   # this fails
        # return [{('background-color: yellow') & ('font-weight: bold')}] * len(s) # this fails

您的输出将是:

相关问题