Styling Pandas Columns
Question:
I am working on a dataframe df. I am trying to set the background color of the cells of the ‘SupTrend’ column. The background should be red when the value in ‘Price’ column is lower than the value in ‘SupTrend’ column, and it should be green otherwise. I tried everything, checked the documentation and I can’t find any explanation or solution for my problem. It seems data inside the function is converted to string and I guess I can’t convert it to float. Does someone knows how to solve this?
def highlight_suptrend(x, data):
return f"background-color: red;" if data['Price'].all() < data['SupTrend'].all() else f"background-color: green;"
df.style.applymap(highlight_suptrend, data=df[['Price', 'SupTrend']], subset=['SupTrend'])
Here is the result:
Answers:
You want to use style.apply
rather than style.applymap
, and then use np.where
for your function return
, selecting red
where Price
is lower than SupTrend
and green
otherwise (using: Series.lt
).
import pandas as pd
import numpy as np
# some mock data
np.random.seed(1)
data = {'Price': np.random.randint(1,11,10),
'SupTrend': np.random.randint(1,11,10)}
df = pd.DataFrame(data)
def highlight_suptrend(x, data):
return np.where(data['Price'].lt(data['SupTrend']),
"background-color: red",
"background-color: green")
df.style.apply(highlight_suptrend,
data=df[['Price', 'SupTrend']],
subset=['SupTrend'])
Result:
I am working on a dataframe df. I am trying to set the background color of the cells of the ‘SupTrend’ column. The background should be red when the value in ‘Price’ column is lower than the value in ‘SupTrend’ column, and it should be green otherwise. I tried everything, checked the documentation and I can’t find any explanation or solution for my problem. It seems data inside the function is converted to string and I guess I can’t convert it to float. Does someone knows how to solve this?
def highlight_suptrend(x, data):
return f"background-color: red;" if data['Price'].all() < data['SupTrend'].all() else f"background-color: green;"
df.style.applymap(highlight_suptrend, data=df[['Price', 'SupTrend']], subset=['SupTrend'])
Here is the result:
You want to use style.apply
rather than style.applymap
, and then use np.where
for your function return
, selecting red
where Price
is lower than SupTrend
and green
otherwise (using: Series.lt
).
import pandas as pd
import numpy as np
# some mock data
np.random.seed(1)
data = {'Price': np.random.randint(1,11,10),
'SupTrend': np.random.randint(1,11,10)}
df = pd.DataFrame(data)
def highlight_suptrend(x, data):
return np.where(data['Price'].lt(data['SupTrend']),
"background-color: red",
"background-color: green")
df.style.apply(highlight_suptrend,
data=df[['Price', 'SupTrend']],
subset=['SupTrend'])
Result: