0

I'd like to apply styling to my the index of my df is some per row criteria is satisfied.

The code I have is

data = {"Labels": ["foo", "bar"], "Values":[1, -1]}
df = pd.DataFrame(data)
df = df.set_index('Labels')
df

I'd like to have a yellow background in the Label column if the value is positive. I tried

df.style.apply(lambda x:  ['background-color: yellow' if x[1]>0 else '', ''])

but no luck. What is that I am doing wrong?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
meto
  • 3,425
  • 10
  • 37
  • 49

2 Answers2

2

x in your lambda function is a pd.Series.

x[1] is just the second value of that series. In your example, just -1. Since -1 > 0, nothing happens.

You probably want to check that for every value of x, as given as example in the docs

df.style.apply(lambda x:['background-color: yellow' if s>0 else '' for s in x])

Also per docs, in Limitations section,

You can only style the values, not the index or columns

rafaelc
  • 57,686
  • 15
  • 58
  • 82
1

As of pandas 1.4.0, you can now apply styling to the index with apply_index()

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.apply_index.html

Unfortunately, I don't know offhand how to apply this styling based on a cell value. It should be possible, though.

I know this is only a partial solution, but this result came up when I searched on how to apply styling to the index, and it's important to know that apply_index() is now available. Hope this helps someone.

Bill
  • 11
  • 1