选择包含多级列名的列

2024-03-28 16:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

当存在多级命名时,如何从数据帧中选择特定列?你知道吗

>>>  x = pd.DataFrame({'instance':['first','first','first'],'foo':['a','b','c'],'bar':rand(3)})
>>> x = x.set_index(['instance','foo']).transpose()
>>> x.columns
MultiIndex
[(u'first', u'a'), (u'first', u'b'), (u'first', u'c')]
>>> x
instance     first                    
foo              a         b         c
bar       0.102885  0.937838  0.907467

(注:这个问题是在this SO question的评论中提出的,评论中也有答案。我觉得把它作为一个问题来讨论会很好。)


Tags: columns数据instancedataframeindexfoo评论bar
1条回答
网友
1楼 · 发布于 2024-03-28 16:22:12

这正是多索引切片器的用途,请参见docshere

In [15]: idx = pd.IndexSlice

In [16]: x.loc[:,idx[:,'a']]
Out[16]: 
instance     first
foo              a
bar       0.525356

In [17]: x.loc[:,idx[:,['a','c']]]
Out[17]: 
instance     first          
foo              a         c
bar       0.525356  0.418152

相关问题 更多 >