Filter Pandas DataFrame based on style

Viewed 639

This documentation shows how to apply styles pandas.DataFrame. How can we select the yellow cells from df?

df = pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": [1, 7, 14, 5, 3]})

def apply_color(v):
    if v % 2 == 0:
        return "background-color: yellow"
    else:
        return ""
df.style.applymap(apply_color)

enter image description here

1 Answers

I am not sure this fully solves the problem, but here is a partial solution

df.style.applymap returns a Styler object: Source.

After displaying the dataframe the style changes are stored in the ctx attribute of the Styler:

So, by assigning the style.applymap to a variable, you can get the Styler

a = df.style.applymap(apply_color)

#then executing:

a

#gives you the dataframe, styled with yellow background

#now, you can access the style by doing


a.ctx

#this returns


defaultdict(list,
        {(0, 0): [''],
         (0, 1): [''],
         (1, 0): ['background-color: yellow'],
         (1, 1): [''],
         (2, 0): [''],
         (2, 1): ['background-color: yellow'],
         (3, 0): ['background-color: yellow'],
         (3, 1): [''],
         (4, 0): [''],
         (4, 1): ['']})

Contributions by E.K.:

find cell ids as follows:

for cell, color in a.ctx.items():
    if 'background-color: yellow' in color:
        print(cell, color, df.iloc[cell])
Related