将样式应用于多索引和多级 pandas 数据框

Applying style to multindex and multilevel pandas dataframe

我有一个 pandas 数据框,当转储到 excel 时显示如下:

我正在尝试在 excel 转储期间实现以下目标:

所以,我正在使用以下代码:

import pandas as pd, numpy as np, sys, os

df = pd.DataFrame()
df['ATC'] =np.random.rand(1, 7).round(2).flatten()
df['P25'] =np.random.rand(1, 7).round(2).flatten()
df['Type1'] = ['A', 'B', 'B', 'A', 'B', 'B', 'A']
df['Type11'] = ['A', 'Aa', 'Bb', 'A', 'Bb', 'B', 'Bb']
df['Type2'] = ['X', 'X', 'X', 'Y', 'Y', 'Y', 'Y']
df = df.pivot_table(index=['Type1', 'Type11'], columns='Type2', aggfunc=[np.mean])['mean']

def color(x):
   c1 = 'background-color: red'
   c2 = 'background-color: green'
   c3 = 'background-color: yellow'
   c = ''

   cols = [('ATC', 'X'), ('P25', 'X')]
   m1 = x[cols].lt(x[('ATC', 'Y')], axis=0)
   m2 = x[cols].gt(x[('P25', 'Y')], axis=0)
   arr = np.select([m1, m2], [c1, c2], default=c3)

   df1 = pd.DataFrame(arr, index=x.index, columns=cols)
   return df1.reindex(columns=x.columns, fill_value=c)

df1 = df.reset_index().style.apply(color,axis=None)
fn = r'C:\Users\Desktop\format_file.xlsx'
ut.removeFile(fn)
df1.to_excel(fn, index=True, engine='openpyxl')

但是我还没有得到想要的输出格式。我现在不关心代码中的颜色,只要我得到格式。

即要求是:

(1) 对于每个 ATC,如果 X < Y 我做到了 green 否则我做到了 blue.

我会这样做:

def color(col):
    colors = ('background-color: blue', 'background-color: green',
              'background-color: yellow')
    c = ''

    l0, l1 = col.name

    # for other columns
    if not (l1 in ['X','Y']): return [''] * len(col)

    l2 = 'X' if l1=='Y' else 'Y'
    others = df[(l0,l2)]
    conds = (others.gt(col), others.lt(col), others.eq(col))

    return np.select(conds, colors, c)


df.style.apply(color)

输出: