【问题标题】:How to conditionally format pandas row groups in jupyter如何在jupyter中有条件地格式化熊猫行组
【发布时间】:2019-08-26 21:48:20
【问题描述】:

我在 pandas 中有一个数据框,看起来有点像这样:

A     B     C
1     0.5   0.6
1     0.7   0.1
2     0.3   0.2
3     0.1   0.3
3     0.2   0.1

当您在 jupyter 中打印 pandas 数据框时,默认输出样式是使用交替的浅色和灰色背景为每一行着色。我希望能够调整每组 A 列值的背景颜色,以便每组具有交替的配色方案。与默认样式非常相似,除了不是每行背景交替灰色和白色,而是按 A 列中的值组交替。

我在这里找到了一些文档:https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html。我不确定如何将这些方法应用于此目的,因为它们似乎要么只与一个单元格元素交互,要么只与一个特定的行交互。

【问题讨论】:

  • 没错。我更新以反映 jupyter 的使用。

标签: python pandas conditional-formatting


【解决方案1】:

试试这个:

def change_color_group(x):
    df = x.copy()
    df.loc[df['A'] == 1, :] = 'background-color: yellow'
    df.loc[df['A']==2,:] = 'background-color: red'
    df.loc[df['A']==3, :] ='background-color: blue'
    return df  


df.style.apply(change_color_group, axis=None)

【讨论】:

    【解决方案2】:

    这是@billy-bonaros 解决方案的通用版本,它为column 中的值组执行交替灰色。最好确保行也按column 值排序:

    def format_color_groups(df, column):
        colors = ['#e8e8e8', '#d6d6cb']
        x = df.copy()
        factors = list(x[column].unique())
        i = 0
        for factor in factors:
            style = f'background-color: {colors[i]}'
            x.loc[x[column] == factor, :] = style
            i = not i
        return x
    

    【讨论】:

      猜你喜欢
      • 2017-05-03
      • 2020-02-09
      • 2021-07-09
      • 1970-01-01
      • 2020-01-12
      • 2020-10-20
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      相关资源
      最近更新 更多