【问题标题】:Pandas change cell color熊猫改变细胞颜色
【发布时间】:2021-08-15 18:15:20
【问题描述】:

如果单元格包含字符串列表中的字符串,我正在尝试更改单元格颜色:

如果有匹配项,我可以更改颜色,但它似乎不会遍历列表中的每个项目,它只执行第一个匹配项(我认为这是因为 ==)

def color_negative_red(val):
    for technique in techniques:
        color = 'green' if val == technique else 'black'
        return 'color: %s' % color

我正在尝试以下方法,但这似乎没有改变任何颜色:

def color_negative_blue(val):
    for technique in techniques:
        color = 'blue' if technique in val else 'black'
        return 'color: %s' % color

我将这些函数称为如下:

s = df1.style.applymap(color_negative_blue)

我希望能够查看项目列表,如果列表中的项目存在,则更改单元格中该文本的颜色。

数据帧:

Column1                Column2              Column3          Column4

Acquire               Infrastructure        Botnet      Drive-by Compromise 
DNS Server                                               Exploit Public-Facing Application  
Domains                                                 External Remote Services    
Server                                                  Hardware Additions  
Virtual Private Server                    Phishing      Spearphishing Attachment
Web Services                              Spearphishing Link
Compromise Accounts Email Accounts                      Spearphishing via Service
Social Media Accounts                                   Replication Through Removable Media 


techniques = ['Server','Web Services', 'Phishing']

【问题讨论】:

    标签: python pandas colors cell


    【解决方案1】:

    当其内容匹配techniques时替换任何单元格:

    def my_func_blue(val):
       if val in techniques:
          return "color: blue"
       else:
          return "color: black"
    
    df.style.applymap(my_func_blue).render()
    

    【讨论】:

    • 我想将它应用到整个 DataFrame 而不仅仅是单个列
    • 这将迭代每一列,因此将函数应用于整个数据帧,一次一列。 cfthe docs
    • 我已更新示例以包含列标题。我在“样式”上遇到 KeyError
    • 哪一列应该包含颜色?
    • 它可能是什么?我想查看单元格,如果列表中有匹配项,则更改颜色
    【解决方案2】:
    def my_func_blue(val):
        if val in techniques:
            color = 'green'
            return f'background-color: {color}'
        else:
            color = 'red'
            return f'background-color: {color}'
    

    上面的代码允许我执行搜索并更改它匹配的单元格的颜色

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-13
      • 2019-01-03
      • 2014-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多