简体   繁体   中英

Panda styler on multiIndex

I want to style a panda DataFrame on a certain index of a multiIndex. Normally, pd.IndexSlice should work according to this answer.

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:

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

Interestingly, I had a similar issue with 0.24.2 but not with 0.23.4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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