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

标签 python pandas dataframe multi-index

假设有一个 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 的样式)所有列 'c3''c2' 元素之间的最小值(或等效的最大值)和'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**

最佳答案

使用GroupBy.transformmin 并按所有值进行比较:

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)

关于python - 在多索引数据帧上突出显示最大/最小值 - Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55688221/

相关文章:

python - 按另一个数据框中的数据排序

python - 如何在 Pandas DataFrame 行上打印列名?

python - Pandas 数字格式,带括号的负数

python访问子类中的父类(super class)变量

python - 没有在 python 中给出所需的输出

python - 在一帧中的 block_wise 索引下连接两个不同长度的数据帧

python - 将每日值合并到日内 DataFrame

python - 加入相同列的 Pandas 数据框并仅获取表 B 中不存在于 A 中的项目

python - 如何在python中将多个netcdf文件合并为一个数据文件

python - 如何让 FactoryBoy 的 ImageField 在调用 save() 之前生成图像?