1

I want apply some filter conditions on specific cols. Based on filter I want to highlight that cell.

I took this example from another post:

styled = (df.style
            .applymap(lambda v: 'background-color: %s' % 'green' if v=='col' else ''))
styled.to_excel('d:/temp/styled.xlsx', engine='openpyxl')

But problem with this is it applies to every cell. So I instead used apply function on a series by converting it to df like below:

df['a'] =df[['a']].style
            .apply(lambda v: 'background-color: %s' % 'green' if v=='col' else '')

In this case when I export df to excel it gives style object rather than values.

If I dont assign that styled result to df['a'] and directly convert to excel then I get desired result with style but then i will get only that column and not entire dataframe

1 Answer 1

3

Use subset parameter for specify column(s) for apply styles:

f = lambda v: 'background-color: %s' % 'green' if v=='col' else ''
df = df.style.applymap(f, subset=['a'])

For negation use Index.difference:

df = df.style.applymap(f, subset=df.columns.difference(['a']))
Sign up to request clarification or add additional context in comments.

6 Comments

Is negation works in subset ? Like Can I provide one col and it should apply to all col but that
@EXODIA - Added solution to answer.
@jezael : We cant apply another style to a styled object ? Like I apply this background based on one filter I want to apply n such more style with diff background. And retain all changes.
Created a new question for that @jezrael stackoverflow.com/questions/67869034/…
@EXODIA - I think not possible, some kind of merging multiple styles based by conditions. Not sure if possible solution is use apply like this
|

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.