How to highlight specific rows based on column value in pandas dataframe
Question:
I’m trying to give a color to whole row if column value exist in a list, but it is not working, below is the code I’m using:
d = {
'ids': ['id1', 'id2', 'id3', 'id4'],
'values': ['Vanilla', 'Chocolate', 'Butterscotch', 'Strawberry']
}
dd = pd.DataFrame(d)
def highlight(row):
if row.ids in ['id1', 'id3']:
return ['background-color: red']
else:
return ''
dd.style.apply(highlight, axis=1)
dd.head()
I have followed the official docs and several answers on SO, doing the same thing but it is not working. I’m working on google colab though…
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.apply.html
Can someone shed some light on this issue?
Answers:
You need to use a vectorial function:
def highlight(row):
return np.where(row.isin(['id1', 'id3']),
'background-color: red', '')
dd.style.apply(highlight)
Output:
whole row
def highlight(df):
return np.tile(np.where(df['ids'].isin(['id1', 'id3']), 'background-color: red', '')[:,None],
(1, df.shape[1]))
dd.style.apply(highlight, axis=None)
Output:
I’m trying to give a color to whole row if column value exist in a list, but it is not working, below is the code I’m using:
d = {
'ids': ['id1', 'id2', 'id3', 'id4'],
'values': ['Vanilla', 'Chocolate', 'Butterscotch', 'Strawberry']
}
dd = pd.DataFrame(d)
def highlight(row):
if row.ids in ['id1', 'id3']:
return ['background-color: red']
else:
return ''
dd.style.apply(highlight, axis=1)
dd.head()
I have followed the official docs and several answers on SO, doing the same thing but it is not working. I’m working on google colab though…
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.apply.html
Can someone shed some light on this issue?
You need to use a vectorial function:
def highlight(row):
return np.where(row.isin(['id1', 'id3']),
'background-color: red', '')
dd.style.apply(highlight)
Output:
whole row
def highlight(df):
return np.tile(np.where(df['ids'].isin(['id1', 'id3']), 'background-color: red', '')[:,None],
(1, df.shape[1]))
dd.style.apply(highlight, axis=None)
Output: