pandas remove observations depending on multi-index level value

279 views Asked by At

I have a multi-index data frame with levels 'id' and 'year':

              value    
id      year           
10      2001   100     
        2002   200         
11      2001   110          
12      2001   200     
        2002   300     
13      2002   210

I want to keep the ids that have values for both years 2001 and 2002. This means I want to obtain:

              value    
id      year           
10      2001   100     
        2002   200         
12      2001   200     
        2002   300      

I know that df.loc[df.index.get_level_values('year') == 2002] works but I cannot extend that to account for both 2001 and 2002. Thanks in advance.

1

There are 1 answers

0
HYRY On BEST ANSWER

How about use groupby and filter:

df.groupby(level=0).filter(
    lambda df:np.in1d([2001, 2002], df.index.get_level_values(1)).all()
)