【问题标题】:Selecting a column with multiple levels of column naming选择具有多级列命名的列
【发布时间】:2014-08-20 00:46:32
【问题描述】:

当存在多级命名时,如何从 DataFrame 中选择特定列?

>>>  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

(注意:这个问题是在 cmets 中向this SO question 提出的,并且 cmets 中也有一个答案。认为将其作为一个问题本身会很好。) em>

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这正是 Multiindex 切片器的用途,请参阅文档here

    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
    

    【讨论】:

    • 世界上真的有人能理解这一点吗?我已经阅读了文档,但它们让我大吃一惊。
    • 另外:0.13.1 有没有办法做到这一点?
    • 在旧版本中,您可以使用.xs(用于单个标签,但在任何级别/轴上),或x.loc[:,x.columns.get_level_values(1).isin(['a','c])] 用于多个
    猜你喜欢
    • 2017-07-07
    • 2019-02-10
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 2012-05-20
    • 2023-03-08
    • 2013-03-25
    • 1970-01-01
    相关资源
    最近更新 更多