2

I'm trying to highlight any row where the cookie flavor is chocolate. How do I do this? I'm trying to use df.style, but not having any luck...

import pandas as pd

Excel_file = "Cookies2.xlsx"

x = pd.read_excel(Excel_file)

sorted_by_Cookie_Boxes_Sold = x.sort_values(['Cookie_Boxes_Sold'], 
ascending=False)

df = pd.DataFrame(sorted_by_Cookie_Boxes_Sold)

df.style

1 Answer 1

1

Try defining the rule first:

def color_chocolate_red(val):
    color = 'red' if val == 'chocolate' else 'black'
    return 'color: {}'.format(color)

Then apply it:

result = df.style.applymap(color_chocolate_red)

For entire row you can use this:

def highlight_row(x):
    df = x.copy()
    mask = df['column'] == 'chocolate'
    df.loc[mask, :] = 'color: red'
    df.loc[~mask,:] = 'color: black'
    return df
Sign up to request clarification or add additional context in comments.

6 Comments

How do I make it appear? Do I write: print(result)?
Exactly like that.
When I try that, the table doesnt appear--only this comes up: <pandas.formats.style.Styler object at 0x0000000009993160>
You must be using Spyder and the styler object can't be rendered in spyder's ipython console.
I'm using a jupyter notebook
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.