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

问题描述

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

在此处输入图像描述

我需要使用格式转储到excel,使其显示为:

在此处输入图像描述

即我有一个字典,用于将颜色应用于列名和索引名。

colorIndex = {'A':'Bb', 'B':'B'}
colorColumn = {'ATC':'X1', 'P25':'Y'}

我正在使用以下代码生成数据框并转储到 excel:

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

def getDF():
   df = pd.DataFrame()
   df['ATC'] =np.random.rand(1, 7).round(2).flatten()
   df['P25'] =np.random.rand(1, 7).round(2).flatten()
   df['P75'] =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', 'X1', 'Y', 'Y', 'Y1', 'Y']
   df = df.pivot_table(index=['Type1', 'Type11'], columns='Type2', aggfunc=[np.mean])['mean']
   return df

df = getDF()
fn = r'C:\Users\Desktop\format_file.xlsx'
df.to_excel(fn, engine='openpyxl')

但我不知道如何为这种 excel 转储生成样式参数。

标签: pandaspython-3.8pandas.excelwriter

解决方案


推荐阅读