Pandas 更改单元格颜色
Pandas change cell color
如果单元格包含字符串列表中的字符串,我将尝试更改单元格颜色:
这允许我在有匹配项时更改颜色,但它似乎没有遍历列表中的每个项目它只匹配第一个(我认为这是因为 ==)
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']
当内容匹配时替换任何单元格 techniques
:
def my_func_blue(val):
if val in techniques:
return "color: blue"
else:
return "color: black"
df.style.applymap(my_func_blue).render()
def my_func_blue(val):
if val in techniques:
color = 'green'
return f'background-color: {color}'
else:
color = 'red'
return f'background-color: {color}'
上面的代码允许我执行搜索并更改匹配的单元格的颜色
如果单元格包含字符串列表中的字符串,我将尝试更改单元格颜色:
这允许我在有匹配项时更改颜色,但它似乎没有遍历列表中的每个项目它只匹配第一个(我认为这是因为 ==)
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']
当内容匹配时替换任何单元格 techniques
:
def my_func_blue(val):
if val in techniques:
return "color: blue"
else:
return "color: black"
df.style.applymap(my_func_blue).render()
def my_func_blue(val):
if val in techniques:
color = 'green'
return f'background-color: {color}'
else:
color = 'red'
return f'background-color: {color}'
上面的代码允许我执行搜索并更改匹配的单元格的颜色