pandas: Boolean indexing with multi index

前端 未结 6 1652
再見小時候
再見小時候 2021-02-08 14:52

There are many questions here with similar titles, but I couldn\'t find one that\'s addressing this issue.

I have dataframes from many different origins, and I want to f

6条回答
  •  你的背包
    2021-02-08 15:26

    If you transform your index 'a' back to a column, you can do it as follows:

    >>> df = pd.DataFrame({'a':[1,1,1,2,2,2,3,3,3], 
                           'b':[1,2,3,1,2,3,1,2,3], 
                           'c':range(9)})
    >>> filt = pd.Series({1:True, 2:False, 3:True})
    >>> df[filt[df['a']].values]
       a  b  c
    0  1  1  0
    1  1  2  1
    2  1  3  2
    6  3  1  6
    7  3  2  7
    8  3  3  8
    

    edit. As suggested by @joris, this works also with indices. Here is the code for your sample data:

    >>> df[filt[df.index.get_level_values('a')].values]
         c
    a b   
    1 1  0
      2  1
      3  2
    3 1  6
      2  7
      3  8
    

提交回复
热议问题