selecting from multi-index pandas

后端 未结 6 467
庸人自扰
庸人自扰 2020-12-02 05:19

I have a multi-index data frame with columns \'A\' and \'B\'.

Is there is a way to select rows by filtering on one column of the multi-index without resetting the

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 05:49

    One way is to use the get_level_values Index method:

    In [11]: df
    Out[11]:
         0
    A B
    1 4  1
    2 5  2
    3 6  3
    
    In [12]: df.iloc[df.index.get_level_values('A') == 1]
    Out[12]:
         0
    A B
    1 4  1
    

    In 0.13 you'll be able to use xs with drop_level argument:

    df.xs(1, level='A', drop_level=False) # axis=1 if columns
    

    Note: if this were column MultiIndex rather than index, you could use the same technique:

    In [21]: df1 = df.T
    
    In [22]: df1.iloc[:, df1.columns.get_level_values('A') == 1]
    Out[22]:
    A  1
    B  4
    0  1
    

提交回复
热议问题