Using the MultiIndex value in a logical selection (during configuration)

There is a similar question here: Pandas using row labels in boolean indexing

But this one uses a simple index, and I cannot figure out how to generalize it to MultiIndex:

df = DataFrame( { 'ssn' : [  489,  489,  220,  220 ],
                  'year': [ 2009, 2010, 2009, 2010 ],
                  'tax' : [  300,  600,  800,  900 ],    
                  'flag': [    0,    0,    0,    0 ] } )

df.set_index( ['ssn','year'], inplace=True )

Semi-trailers solutions:

df.flag[ (df.year ==2010) & (df.tax<700) ] = 9 (works if drop = False in set_index)

df.flag[ (df.index==2010) & (df.tax<700) ] = 9 (works for a simple index)

I tried several things, but I just can't figure out how to generalize from a simple index to a multi. For instance. df.index.year = 2010 and 20 more guesses ...

+4
source share
1 answer

You can use index.get_level_values()for example.

df.flag[(df.index.get_level_values('year') == 2010) & (df.tax < 700)] = 9
+3
source

All Articles