根据样式筛选 Pandas DataFrame

Filter Pandas DataFrame based on style

documentation 展示了如何应用样式 pandas.DataFrame。我们如何 select 来自 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)

我不确定这是否完全解决了问题,但这是部分解决方案

df.style.applymap returns 一个 Styler 对象:Source.

显示数据框后,样式更改存储在 Styler 的 ctx 属性中:

因此,通过将 style.applymap 分配给变量,您可以获得 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): ['']})

E.K. 的贡献:

查找小区id如下:

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