pandas - 将样式应用于多索引和多级熊猫数据框
问题描述
我有一个 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)
输出:
推荐阅读
- http - 什么是有效的 RFC1123 日期格式
- telegram - 将 TelegramDesktop 配置文件转换为 telegram-cli
- javascript - AJAX 不发送数据,我不能使用 POST Result
- javascript - Angular 绑定中的 Unicode 字符
- java - 如何排除 IntelliJ 中的不安全删除?
- java - 为什么我们需要在 PACT 测试中进行单元测试?
- vb.net - 在每个循环中跳过一行,并带有一个排好序的列
- javascript - 测试开关案例 - 单元测试
- c#-4.0 - Sandcastle 帮助文件生成器 (SHFB)。控制在源代码文件的帮助文件中添加/不添加类
- go - 找不到提供包的模块