2

I have a MultiIndex Pandas dataframe which looks like this:

col1    col2    col3
a       e       m
b       f       n
        g       o
c       h       p
        i       q
d       j       r
        k       s
        l       t

The MultiIndex consists of col1 and col2.

How can I select the "rows" of col1 which hold exactly two index labels in col2?

I.e., I want:

col1    col2    col3
b       f       n
        g       o
c       h       p
        i       q

2 Answers 2

6

Use the group by filter

df.groupby('col1').filter(lambda x: len(x) == 2)

          col3
col1 col2     
b    f       n
     g       o
c    h       p
     i       q
Sign up to request clarification or add additional context in comments.

Comments

2

IIUC

s=df.groupby(level=0).size()

df.loc[s[s==2].index.tolist()]
Out[583]: 
          col3
col1 col2     
b    f       n
     g       o
c    h       p
     i       q

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.