-->

Pandas Get All Values from Multiindex levels

2020-04-16 08:18发布

问题:

Given the following pivot table:

df=pd.DataFrame({'A':['a','a','a','a','a','b','b','b','b'],
                 'B':['x','y','z','x','y','z','x','y','z'],
                 'C':['a','b','a','b','a','b','a','b','a'],
                 'D':[7,5,3,4,1,6,5,3,1]})
table = pd.pivot_table(df, index=['A', 'B','C'],aggfunc='sum')
table

            D
A   B   C   
a   x   a   7
        b   4
    y   a   1
        b   5
    z   a   3
b   x   a   5
    y   b   3
    z   a   1
        b   6

I'd like to access each value of 'C' (or level 2) as a list to use for plotting. I'd like to do the same for 'A' and 'B' (levels 0 and 1) in such a way that it preserves spacing so that I can use those lists as well. I'm ultimately trying to use them to create something like this via plotting:

Here's the question from which this one stemmed.

Thanks in advance!

回答1:

You can use get_level_values to get the index values at a specific level from a multi-index:

In [127]:
table.index.get_level_values('C')

Out[127]:
Index(['a', 'b', 'a', 'b', 'a', 'a', 'b', 'a', 'b'], dtype='object', name='C')

In [128]:    
table.index.get_level_values('B')

Out[128]:
Index(['x', 'x', 'y', 'y', 'z', 'x', 'y', 'z', 'z'], dtype='object', name='B')

In [129]:
table.index.get_level_values('A')

Out[129]:
Index(['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], dtype='object', name='A')

get_level_values accepts an int param for the level or a label

Note that for the higher levels, the values are repeated to correspond with the index length at the lowest level, for display purposes you don't see this