pandas: Boolean indexing with multi index

前端 未结 6 1659
再見小時候
再見小時候 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:14

    If the boolean series is not aligned with the dataframe you want to index it with, you can first explicitely align it with align:

    In [25]: df_aligned, filt_aligned = df.align(filt.to_frame(), level=0, axis=0)
    
    In [26]: filt_aligned
    Out[26]:
             0
    a b
    1 1   True
      2   True
      3   True
    2 1  False
      2  False
      3  False
    3 1   True
      2   True
      3   True
    

    And then you can index with it:

    In [27]: df[filt_aligned[0]]
    Out[27]:
         c
    a b
    1 1  0
      2  1
      3  2
    3 1  6
      2  7
      3  8
    

    Note: the align didn't work with a Series, therefore the to_frame in the align call, and therefore the [0] above to get back the series.

提交回复
热议问题