I am trying to highlight the single whole cell in pandas based on text. For example, if Recommend is 'SELL', I want to highlight in red and green for 'BUY'. Appreciate if someone can guide me on this.
def color_negative_red(value):
if value < 0:
color = 'red'
elif value > 0:
color = 'green'
else:
color = 'black'
return 'color: %s' % color
import pandas as pd
data = {'Stock': ['TSLA','GM','GOOG','MMM'],
'Diff': [-200,-50,150,50],
'Recommend' : ['SELL','SELL','BUY','BUY']
}
df = pd.DataFrame(data, columns = ['Stock', 'Diff', 'Recommend'])
df.style.applymap(color_negative_red, subset=['Diff'])
### how to get a conditional highlight based on 'Recommend' ?????
Styles can be chained together. There are many ways to solve this problem, assuming 'BUY' and 'SELL' are the only options np.where
+ apply
is a good choice:
def color_recommend(s):
return np.where(s.eq('SELL'),
'background-color: red',
'background-color: green')
(
df.style.applymap(color_negative_red, subset=['Diff'])
.apply(color_recommend, subset=['Recommend'])
)
Alternatively in a similar way to color_negative_red
:
def color_recommend(value):
if value == 'SELL':
color = 'red'
elif value == 'BUY':
color = 'green'
else:
return
return f'background-color: {color}'
(
df.style.applymap(color_negative_red, subset=['Diff'])
.applymap(color_recommend, subset=['Recommend'])
)
You are almost there!
def color_negative_red(value):
if value < 0:
color = 'pink'
elif value > 0:
color = 'lightgreen'
else:
color = 'white'
return 'background-color: %s' % color
import pandas as pd
data = {'Stock': ['TSLA','GM','GOOG','MMM'],
'Diff': [-200,-50,150,50],
'Recommend' : ['SELL','SELL','BUY','BUY']
}
df = pd.DataFrame(data, columns = ['Stock', 'Diff', 'Recommend'])
df.style.applymap(color_negative_red, subset=['Diff'])
Only change needed is color needs to become background-color: return 'background-color: %s' % color
If you wanted to highlight the entire row, try:
def color_negative_red(row):
print(row)
value = row.loc["Diff"]
if value < 0:
color = 'pink'
elif value > 0:
color = 'lightgreen'
else:
color = 'black'
return ['background-color: %s' % color for r in row]
import pandas as pd
data = {'Stock': ['TSLA','GM','GOOG','MMM'],
'Diff': [-200,-50,150,50],
'Recommend' : ['SELL','SELL','BUY','BUY']
}
df = pd.DataFrame(data, columns = ['Stock', 'Diff', 'Recommend'])
df.style.apply(color_negative_red, axis=1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With