Skip to content

Instantly share code, notes, and snippets.

@AayushSameerShah
Last active May 31, 2021 11:58
Show Gist options
  • Save AayushSameerShah/330d000dfa9b245646391d1c5f167147 to your computer and use it in GitHub Desktop.
Save AayushSameerShah/330d000dfa9b245646391d1c5f167147 to your computer and use it in GitHub Desktop.
This is the HACK to highlight cells in pandas based on a condition
# Wow way
df[(np.abs(df) > 2).any(1)].style.applymap(lambda x: "background: yellow" if np.abs(x) > 2 else "")
# ↑ Here applymap is used which
# is eqivalent to the code below
# Verbose, but still more control way
df[(np.abs(df) > 2).any(1)].style.apply(lambda x: ["background: yellow" if np.abs(value) > 2 else "" for value in x])
# ↑ Only apply is used, so needed to itereate over all elements in this ↑ list comp way
# Best EVER! Style based on the positions! (BEST BEST BEST)
def styling_specific_cell(df, rows, cols):
df_styler = pd.DataFrame('', index= df.index, columns= df.columns)
df_styler.iloc[rows, cols] = 'background-color: red'
return df_styler
left.style.apply(styling_specific_cell, rows= [0, 2], cols= [0, 2], axis= None)
# ↑ This is required
'''
Need to remember this that, the styling works is such a way that YOU NEED TO PASS value for EACH CELL.
No matter whether it meets a condition or not. IF NOT just pass "" or pass color
In the 3rd example, we are makeing one DF for style. That is the matrix by itself.
When it is being created, we filled it with '' and then only filled color in the cell
where we gave the positions.
Then it returned the DF and applied.
REMEMBER: THIS WILL ONLY WORK WHEN `axis= None` IS PASSED. (As it passes WHOLE DF - not Series by Series)
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment