Pandas Get All Values from Multiindex levels

十年热恋 提交于 2019-12-02 01:59:38

问题


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



来源:https://stackoverflow.com/questions/37190938/pandas-get-all-values-from-multiindex-levels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!