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)
CodePudding user response:
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))
CodePudding user response:
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