0

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?

1
  • change df['column'] == 'chocolate' to df['ids'].isin(['id1', 'id3']) Commented Dec 8, 2022 at 9:00

1 Answer 1

2

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:

enter image description here

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:

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

any way to highlight whole row instead of just 1 column?
Thank you!! just one thing, the colours doesn't persist when I go to next cell and run dd or dd.head(), it outputs with normal color, actually, I need to save the df as csv/excel WITH colours...
You have to chain style.apply commands if needed, or with to_excel, style does NOT modify the DataFrame in a persistant way but returns a special object

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.