How do I change the color of the Age
column if the condition that the value is equal to 33
is met?
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.
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:
# 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:
(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.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.