简体   繁体   English

多索引上的Panda Styler

[英]Panda styler on multiIndex

I want to style a panda DataFrame on a certain index of a multiIndex. 我想在multiIndex的某个索引上设置熊猫DataFrame的样式。 Normally, pd.IndexSlice should work according to this answer. 通常,pd.IndexSlice应该根据答案工作。

However, as shown below, this does not seem to work: 但是,如下所示,这似乎不起作用:

import pandas as pd
import itertools
import numpy as np
cv = ['data1_1','data1_2','data1_3']
param = ['data2_1', 'data2_2']
combi = tuple(itertools.product(cv,param))
columns = pd.MultiIndex.from_tuples(combi)
myData = pd.DataFrame(np.zeros((4,6), dtype=bool)*False, columns = columns)

myData.iloc[0,0] = True

def highligh(val):
    if val == True:
        color = 'red'
    else:
        color = 'white'
    return 'background-color: {}'.format(color)

myColoredData = myData.style.apply(highligh, subset=pd.IndexSlice[:,pd.IndexSlice[:,'data2_2']])


import seaborn as sns
cm = sns.light_palette("green", as_cmap=True)
myColoredData2 = myData.style.background_gradient(cmap=cm, subset=pd.IndexSlice[:,pd.IndexSlice[:,'data2_2']])

myData.loc[pd.IndexSlice[:,pd.IndexSlice[:,'data2_2']]]

myColoredData.to_excel('colored.xlsx')
myColoredData2.to_excel('colored2.xlsx')

The to_excel method is throwing me an error: to_excel方法抛出一个错误:

unhashable type: 'slice' 不可散列的类型:“切片”

As of now, this does not seem to work, as stated here : 截至目前,这似乎并没有工作,因为这里所说

Note that this indexer previously worked in pandas version 0.22, but a regression has been introduced in 0.24.2 请注意,此索引器以前在pandas版本0.22中可用,但是在0.24.2中引入了回归功能

Interestingly, I had a similar issue with 0.24.2 but not with 0.23.4. 有趣的是,我在0.24.2上遇到了类似的问题,但在0.23.4上却没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM