在多索引数据帧上突出显示最大/最小值 - Pandas

2023-12-08

假设有一个 2 层 MultiIndex 数据框:

df = pd.DataFrame([['one', 'A', 100,3], ['two', 'A', 101, 4], 
                   ['three', 'A', 102, 6], ['one', 'B', 103, 6], 
                   ['two', 'B', 104, 0], ['three', 'B', 105, 3]],
   columns=['c1', 'c2', 'c3', 'c4']).set_index(['c1', 'c2']).sort_index()
print(df)

看起来像这个

           c3  c4
c1    c2         
one   A   100   3
      B   103   6
three A   102   6
      B   105   3
two   A   101   4
      B   104   0

我的目标是突出显示(使用 Pandas 的样式)元素之间的最小值(或等效的最大值)'c2'对于所有列'c3' and 'c4'对于中的每个元素'c1'

             c3      c4
c1    c2         
one   A   **100**   **3**
      B     103       6
three A   **102**     6
      B     105     **3**
two   A   **101**     4
      B     104     **0**

您有什么建议吗?

我已经尝试过这个,但它是按列工作的,而不是基于索引。

def highlight_min(data):

    attr = 'background-color: {}'.format(color)

    if data.ndim == 1:  # Series from .apply(axis=0) or axis=1
        is_max = data == data.min()
        return [attr if v else '' for v in is_max]
    else:  # from .apply(axis=None)
        is_max = data == data.min().min()
        return pd.DataFrame(np.where(is_max, attr, ''),
                            index=data.index, columns=data.columns)

df = df.style.apply(highlight_min, axis=0)

结果如果如下

             c3      c4
c1    c2         
one   A   **100**     3
      B     103       6
three A     102       6
      B     105       3
two   A     101       4
      B     104     **0**

Use GroupBy.transform with min并按所有值进行比较:

def highlight_min(data):
    color= 'red'
    attr = 'background-color: {}'.format(color)

    if data.ndim == 1:  # Series from .apply(axis=0) or axis=1
        is_min = data == data.min()
        return [attr if v else '' for v in is_min]
    else: 
        is_min = data.groupby(level=0).transform('min') == data
        return pd.DataFrame(np.where(is_min, attr, ''),
                            index=data.index, columns=data.columns)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在多索引数据帧上突出显示最大/最小值 - Pandas 的相关文章

随机推荐