将样式应用于multindex和多级熊猫数据框

时间:2020-05-21 11:30:51

标签: pandas python-3.8 pandas.excelwriter

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

enter image description here

但是我试图在excel转储期间实现以下目标:

enter image description here

因此,我正在使用以下代码:

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')

但是我无法获得所需的输出格式。只要获得格式,我现在就不在乎代码中的颜色。

即要求是:

对于每个ATC

(1),如果X < Ygreen,我是blue

1 个答案:

答案 0 :(得分:1)

这就是我要做的:

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)

输出:

df.style.apply(color)