我正在迭代一个多索引数据帧,并try 将特定单元格的 colored颜色 设置为两个变量points_colorstat_color中的样式.

100

for metric, new_df in df3.groupby(level=0):
    idx = pd.IndexSlice
    row = new_df.loc[(metric),:]
    for geo in ['US', 'UK']:
        points_color, stat_color = color(new_df.loc[metric,idx[:,:,['difference']]][geo]['']['difference'],
                                   new_df.loc[metric,idx[:,:,['stat']]][geo]['']['stat'])
        

#####  SEE HERE  #######
        df3.loc[metric,idx[:,:,['points']]][geo]['GM']['points'] = # apply points_color style to this value df3.loc[metric,idx[:,:,['points']]][geo]['GM']['points']
        df3.loc[metric,idx[:,:,['stat']]][geo]['']['stat'] = # apply stat_color style to this value df3.loc[metric,idx[:,:,['stat']]][geo]['']['stat']
###########

df3

Setup for the dataframe:

dic = {'US':{'Quality':{'points':"-2 n", 'difference':'equal', 'stat': 'same'}, 'Prices':{'points':"-7 n", 'difference':'negative', 'stat': 'below'}, 'Satisfaction':{'points':"3 n", 'difference':'positive', 'stat': 'below'}},
      'UK': {'Quality':{'points':"3 n", 'difference':'equal', 'stat': 'above'}, 'Prices':{'points':"-13 n", 'difference':'negative', 'stat': 'below'}, 'Satisfaction':{'points':"2 n", 'difference':'negative', 'stat': 'same'}}}
d1 = defaultdict(dict)
for k, v in dic.items():
    for k1, v1 in v.items():
        for k2, v2 in v1.items():
            d1[(k, k2)].update({k1: v2})

df = pd.DataFrame(d1)

df.columns = df.columns.rename("Skateboard", level=0)
df.columns = df.columns.rename("Metric", level=1)

df3 = pd.concat([df], keys=[''], names=['Q3'], axis=1).swaplevel(0, 1, axis=1)
df3.columns = df3.columns.map(lambda x: (x[0], 'GM', x[2]) if x[2] == 'points' else x)
df3.insert(loc=0, column=('','', 'Mode'), value="Website")

df3

Setup for the color function:它接受两个单元格值Difference和Stat,并确定单元格点和统计数据的样式是否在数据帧中.

def color(difference, stat):
    points_color, stat_color = '', ''
    
    if stat in ('below', 'above'):
        stat_color = 'background-color: #f2dcdb; color: red'
    
    if difference == "negative":
        points_color = 'color: red'
    elif difference == "positive":
        points_color = 'color: green' 
    
    return points_color, stat_color

推荐答案

您可以按列表 Select geo列,比较statdifference,并按切片设置值:

def color(x):
    
    idx = pd.IndexSlice
    geo = ['US', 'UK']
    
    m1 = x.loc[:, idx[geo, :, 'stat']].isin(('below', 'above'))
    diff = x.loc[:, idx[geo, :, 'difference']]
    
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    
    diff = (diff.rename(columns={'difference':'points'}, level=2)
                 .rename(columns={'':'GM'}, level=1))
    df1.loc[:, idx[geo, 'GM', 'points']] = np.select([diff.eq('negative'), 
                                                      diff.eq('positive')], 
                                                     ['color: red','color: green'], '')
    df1.loc[:, idx[geo, :, 'stat']] = np.where(m1, 
                                           'background-color: #f2dcdb; color: red', '')
                     
    return df1

df.style.apply(color, axis=None)

Python相关问答推荐

处理(潜在)不断增长的任务队列的并行/并行方法

我们可以为Flask模型中的id字段主键设置默认uuid吗

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

如何从数据库上传数据到html?

在vscode上使用Python虚拟环境时((env))

从spaCy的句子中提取日期

未知依赖项pin—1阻止conda安装""

如何从列表框中 Select 而不出错?

使用BeautifulSoup抓取所有链接

pandas:对多级列框架的列进行排序/重新排序

从旋转的DF查询非NaN值

判断Python操作:如何从字面上得到所有decorator ?

GPT python SDK引入了大量开销/错误超时

Python Mercury离线安装

我什么时候应该使用帆布和标签?

多个矩阵的张量积

如何在Django模板中显示串行化器错误

运行从Airflow包导入的python文件,需要airflow实例?

如何将ManyToManyfield用于Self类

根据两个lambda条件筛选组并根据条件创建新列的最佳方式是什么?