Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas style object with multi-index

I am formatting a pandas dataframe with styler to highlight columns and format numbers. I also want to apply multi-index for more clear, pleasant and easy to read. Since I apply Styler to subset of columns it does not work work with the multi-index.

Example:

arrays = [np.hstack([['One']*2, ['Two']*2]) , ['A', 'B', 'C', 'D']]
columns = pd.MultiIndex.from_arrays(arrays)
data =  pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD'))
data.columns = columns 
import seaborn as sns
cm = sns.light_palette("green", as_cmap=True)
data.style.background_gradient(cmap=cm, subset=['A'])

Is there a way to subset the columns so the styler can work. According to the below sources this is implemented but there is not examples so it is hard to me to understand how to apply it: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.formats.style.Styler.html https://github.com/pandas-dev/pandas/issues/11655

thank you !

like image 663
Maria Petrova Avatar asked Jan 19 '17 09:01

Maria Petrova


People also ask

How do I use conditional formatting in pandas?

One way to conditionally format your Pandas DataFrame is to highlight cells which meet certain conditions. To do so, we can write a simple function and pass that function into the Styler object using . apply() or .

Can a Dataframe have multiple indexes?

A multi-index (also known as hierarchical index) dataframe uses more than one column as the index of the dataframe. A multi-index dataframe allows you to store your data in multi-dimension format, and opens up a lot of exciting to represent your data.


2 Answers

I think you can use pd.IndexSlice[...] method:

data.style.background_gradient(cmap=cm, subset=pd.IndexSlice[:, pd.IndexSlice[:, 'A']])

Demo:

In [5]: data.loc[pd.IndexSlice[:, pd.IndexSlice[:, 'A']]]
Out[5]:
        One
          A
0 -0.808483
1  0.009371
2  0.977138
3 -0.875554
4 -0.052424

In [6]: data
Out[6]:
        One                 Two
          A         B         C         D
0 -0.808483 -2.280683  0.576145  0.649688
1  0.009371  0.721510  1.013764 -0.157493
2  0.977138  1.441392  1.718618 -0.320826
3 -0.875554 -1.060507  1.457075  0.570195
4 -0.052424 -0.742842 -0.203830 -1.202091

in Jupyter:

enter image description here

like image 141
MaxU - stop WAR against UA Avatar answered Oct 13 '22 08:10

MaxU - stop WAR against UA


Here, is another way:

data.style.background_gradient(cmap=cm, subset=data.columns.get_loc_level('A', level=1)[0])

Output:

enter image description here

like image 22
Scott Boston Avatar answered Oct 13 '22 06:10

Scott Boston