Search code examples
pandasdataframemulti-index

Filtering in a multi index pandas data frame


I have the following table with two indexes NSRCODE and PBL_AWI.

NSRCODE  PBL_AWI          Area           
CM                        56454567489672
         BONS             44705.492941
         BTNN            253854.591990
         FONG             41625.590370
         FONS             16814.159680
         Lake             57124.819333
         River             1603.906642
         SONS            583958.444751
         STNN             45603.837177
         clearcut        106139.013930
         disturbed       127719.865675
         lowland         118795.578059
         upland         2701289.270193
LBH                      97657564123186
         BFNN            289207.169650
         BONS           9140084.716743
         BTNI             33713.160390
         BTNN          19748004.789040
         FONG           1687122.469691
         FONS           5169959.591270
         FTNI            317251.976160
         FTNN           6536472.869395
         Lake            258046.508310
         River            44262.807900
         SONS           4379097.677405
         burn regen      744773.210860
         clearcut         54066.756790
         disturbed       597561.471686
         lowland       12591619.141842
         upland        23843453.638117

I am wondering, how can I filter the first entries for each NSRCODE (where PBL_AWI is empty) such that I am left with the rest of the table?


Solution

  • Use Index.get_level_values with Index.duplicated:

    m = df.index.get_level_values('NSRCODE').duplicated()
    
    df1 = df[m]