首页 > 解决方案 > 将样式应用于多索引和多级熊猫数据框

问题描述

我有一个 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

标签: pandaspython-3.8pandas.excelwriter

解决方案


这是我要做的:

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(颜色)


推荐阅读