【问题标题】:How to color boolean values by different colors in pandas dataframe如何在熊猫数据框中用不同颜色为布尔值着色
【发布时间】:2019-04-11 17:45:06
【问题描述】:
Customer_id   Name    Age  Balance
        Q1   True   True     True
        W2   True   True     True
        E3   True  False     True
        T5   True   True    False
        Y6   True   True     True
        U7   True   True     True
        I8  False  False    False
        O9   True  False    False
        P0  False  False    False

我想在上面的数据框中用黄色突出显示或着色单词'TRUE'

这是我尝试过的代码:

def color_negative_red(val):
    color = 'yellow' if val == 'TRUE' else 'black'
    return 'color: %s' % color
df = dataframe.style.\
       apply(color_negative_red).\
       to_excel('df.xlsx')

我收到以下错误

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index Customer_id')

我在这里做错了什么?

【问题讨论】:

    标签: python pandas dataframe colors highlight


    【解决方案1】:

    使用Styler.applymap 代替apply:

    dataframe.style.\
           applymap(color_negative_red).\
           to_excel('df.xlsx')
    

    您还可以通过True(如果是布尔值)和'True'(如果是字符串)进行比较:

    def color_negative_red(val):
        color = 'yellow' if val == True else 'black'
        return 'color: %s' % color
    
    #python 3.6+ with f-strings
    def color_negative_red(val):
        color = 'yellow' if val == True else 'black'
        return f'color: {color}'
    
    #python bellow 3.6
    def color_negative_red(val):
        color = 'yellow' if val == True else 'black'
        return 'color: {}'.format(color)
    

    如果还想删除索引值:

    dataframe.style.\
           applymap(color_negative_red).\
           to_excel('df.xlsx', index=False)
    

    【讨论】:

      【解决方案2】:

      试试这个(这里你可以使用apply):

      def f(x):
          df = x.copy()
          for i in df.columns:
              df.loc[df[i]=='TRUE',i]=='background-color: yellow'
          return df    
      
      df=df.style.apply(f, axis=None)
      

      【讨论】:

      • 使用上一个带有applymap的代码,'True'和'FALSE'的背景颜色都变黑了
      • @pytorch 已编辑评论,那么现在呢?
      猜你喜欢
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      • 2021-06-06
      • 2020-05-15
      • 2021-11-25
      相关资源
      最近更新 更多