pandas 从Multiindex级别获取所有价值 [英] Pandas Get All Values from Multiindex levels
问题描述
给出以下数据透视表:
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
我想访问"C"(或2级)的每个值作为列表进行绘图. 我想对"A"和"B"(级别0和1)执行相同的操作,以使其保留间距,以便我也可以使用这些列表.我最终试图通过绘图使用它们来创建类似的东西:
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:
提前谢谢!
推荐答案
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
接受级别或标签的int参数
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
这篇关于 pandas 从Multiindex级别获取所有价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!