简体   繁体   English

如果年龄等于数字,Python Pandas 如何更改背景颜色?

[英]Python Pandas how to change background color if age is equal to a number?

How do I change the color of the Age column if the condition that the value is equal to 33 is met?如果满足值等于33的条件,如何更改Age列的颜色?

My code:我的代码:

import pandas as pd

df = pd.DataFrame.from_dict(
    {
        "Nombre": ["Mike", "Jordan", "John"],
        "Age": [33, 45, 20],
        "Lugar": ["Arg", "Pol", "Ind"]
    }
)
def _color_red_or_green(val):
    color = 'red' if val != 33 else 'green'
    return 'color: %s' % color

df.style.applymap(_color_red_or_green)

print(df)

if you need to make the color red when you inputs 33, then you need to make this change.如果您需要在输入 33 时将颜色变为红色,则需要进行此更改。

val == 33

Instead of代替

val != 33

This is the final code just incase:这是以防万一的最终代码:

import pandas as pd

df = pd.DataFrame.from_dict(
    {
        "Nombre": ["Mike", "Jordan", "John"],
        "Age": [33, 45, 20],
        "Lugar": ["Arg", "Pol", "Ind"]
    }
)
def _color_red_or_green(val):
    color = 'red' if val == 33 else 'green'
    return 'color: %s' % color

df.style.applymap(_color_red_or_green)

print(_color_red_or_green(33))

If you're looking to change the color of the Age column only, try this:如果您只想更改 Age 列的颜色,请尝试以下操作:

# only style the Age column
df.style.applymap(_color_red_or_green, subset=['Age'])

Depending on what you want to color, one of two options are possible:根据您要着色的内容,可以选择以下两个选项之一:

# change color of values
def _color_red_or_green(val):
    color = 'red' if val == 33 else 'green'
    return 'color: %s' % color

在此处输入图像描述

# change color of cells
def _color_red_or_green(val):
    color = 'red' if val == 33 else 'green'
    return 'background: %s' % color

在此处输入图像描述

Make it easy and convenient by using the functions that already exist, instead of using applymap:使用已经存在的函数,而不是使用 applymap,让它变得简单方便:

(df.style
 .set_properties(subset=["Age"], background="lightgreen")
 .highlight_between(subset=["Age"], color="pink", left=33, right=33)
)

(You can of course use other colors if wanted - for background I picked lighter variants of red and green.) (如果需要,您当然可以使用 其他颜色- 作为背景,我选择了较浅的红色和绿色变体。)

在此处输入图像描述

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

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