So I have a dataframe which looks like:
Target, Achieved, Goal, Remaining
10, 5, 50, 5
4, 5, 125, 0
3, 3, 100, 0
8, 2, 25, 6
I want to display this dataframe with visible info based on colors, Under this criteria:
- If goal is achieved I just wanted row to be green regardless of how surpassed goal actually is. So the whole 2nd and 3rd rows would be the same green color
- If goal is not achieved, I want to color them based on heatmap. So here I want 4th row to be a darker shade (of lets say red) than 1st row since I am missing more on that row's goal.
For single color, following function works perfectly: Thanks to the answer here
def highlight_col(x):
#copy df to new - original data are not changed
df = x.copy()
#set by condition
mask = df['Goal Completion (%)'] >= 100
df.loc[mask, :] = 'background-color: lightgreen'
df.loc[~mask,:] = 'background-color: pink'
return df
For a simple heatmap without excluding Goal completion condition, its possible via:
df.style.background_gradient(cmap='Reds')
But it:
- Includes whole dataframe
- Color by each column separately
- Cannot exclude rows with goals achieved
- Could not be used inside my above function (tried using:
df.loc[~mask,:] = 'background_gradient: Reds'
in last line but didn't work either.
P.S. My Dataframe isn't very large so I prefer table coloring itself from where I can select rows instead of having a whole new viz. Any suggestions bettering the situation are highly welcomed!