首页 > 解决方案 > 突出显示python中的文本和列

问题描述

在 python 中设置文本和列的样式

数据框中的示例片段

df1 = {
    'IncNum':['1','2','3'],
    'Text_Col':['sample text','sample text containing the keywords to be highlighted','highlighted values'],
    'Outcome': ['True','False','True']
}

df1 = pd.DataFrame(df1)

我试图在 Text_Col 中突出显示特定行和一些关键字,任何关于如何实现相同的指针

关键字 = ['sample','text'] --> 应该为列 Text_col 进行颜色编码

def highlight(s):
    if s.Outcome == "True":
        return ['background-color: yellow']*len(df1.columns)
    else:
        return ['background-color: white']*len(df1.columns)

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

标签: pythonpandas

解决方案


使用Styler.apply函数返回样式的 DataFrame,还检查是否不是布尔值Outcome- 然后解决方案是必要的使用m1 = x['Outcome']

def color(x): 
   c1 = 'background-color: yellow'
   c = ''

   #if True are strings
   m1 = x['Outcome'] == "True"

   #if True are boolean
   #m1 = x['Outcome']

   df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
   df1.loc[m1, :] = c1
   return df1

df1.style.apply(color,axis=None)

推荐阅读