简体   繁体   English

如何根据 Python pandas DataFrame 中的单元格的值对不同的单元格进行着色

[英]How to color different cells based on the value of the cells in a Python pandas DataFrame

I have a pandas DataFrame with different string values to be filled by different colors.我有一个 pandas DataFrame 有不同的字符串值,由不同的 colors 填充。 For the following DataFrame df , all I want is that different cells are in different colors.对于以下 DataFrame df ,我想要的是不同的单元格位于不同的 colors 中。 For example, the cells that have 'A' value is in red, the cells that have 'B' value is in green, and 'C' in blue, 'D' in grey, etc.例如,具有“A”值的单元格为红色,具有“B”值的单元格为绿色,“C”为蓝色,“D”为灰色等。

df=pd.DataFrame({'a':['A','B','D'],'b':['E','B','C'],'c':['F','A','D']})

How can I achieve this using the Styler.apply ?如何使用Styler.apply实现这一点? Any thoughts?有什么想法吗?

try:尝试:

col_dict = {'A': 'red', 'B': 'green', 'C': 'blue', 'D': 'gray'}
def colour_cell(val):
    if val in col_dict:
        return 'Background-color: %s' % col_dict[val]
    return ''

df.style.applymap(colour_cell)

One liner solution(assuming if all the values will have color assigned to it):一种衬里解决方案(假设所有值都分配有颜色):

df.style.applymap(lambda v: 'Background-color: %s' % col_dict[v])

在此处输入图像描述

You could use Styling with a dictionary of colors you want to map values to:您可以将样式与您想要 map 值的 colors 字典一起使用:

import pandas as pd

d = {'a': ['A', 'B', 'D'], 'b': ['E', 'B', 'C'], 'c': ['F', 'A', 'D']}
df = pd.DataFrame(data=d)
df

ex2

color_mapping = {'A': 'red', 'B': 'green', 'C': 'blue', 'D': 'gray', 'E': 'indigo', 'F': 'violet'}
df.style.applymap(lambda v: f"color: {color_mapping.get(v, 'black')}")

ex3

If you want the cells to be filled in with the color use background-color rather than color :如果您希望使用颜色填充单元格,请使用background-color而不是color

df.style.applymap(lambda v: f"background-color: {color_mapping.get(v, 'black')}")

ex4

In case you want to set background color and the text color to white for better readability:如果您想将背景颜色和文本颜色设置为白色以获得更好的可读性:

df.style.applymap(lambda v: f"background-color: {color_mapping.get(v, 'black')}").applymap(lambda _: "color: white")

前5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM