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

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
EXODIA
  • 908
  • 3
  • 10
  • 28

1 Answers1

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']))
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 1
    Is negation works in subset ? Like Can I provide one col and it should apply to all col but that – EXODIA Jun 04 '21 at 08:19
  • @EXODIA - Added solution to answer. – jezrael Jun 04 '21 at 08:33
  • @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. – EXODIA Jun 07 '21 at 09:03
  • Created a new question for that @jezrael https://stackoverflow.com/questions/67869034/styler-object-has-no-attribute-style – EXODIA Jun 07 '21 at 10:44
  • @EXODIA - I think not possible, some kind of merging multiple styles based by conditions. Not sure if possible solution is use `apply` like [this](https://stackoverflow.com/a/67534320/2901002) – jezrael Jun 07 '21 at 10:48
  • @jezael: that is not doing the work correctly. – EXODIA Jun 07 '21 at 11:29