Amelio Vazquez-Reina
Amelio Vazquez-Reina

Reputation: 96478

Nested indexing of multi-index dataframes

Say I have the following dataframe df with three levels as a multi-index:

                         A         B         C
X      Y     Z                          
bar   one    a   -0.007381 -0.365315 -0.024817
             b   -1.219794  0.370955 -0.795125
baz   three  a    0.145578  1.428502 -0.408384
             b   -0.249321 -0.292967 -1.849202
      two    a   -0.249321 -0.292967 -1.849202
      four   a    0.21     -0.967123  1.202234
foo   one    b   -1.046479 -1.250595  0.781722
             a    1.314373  0.333150  0.133331
qux   two    c    0.716789  0.616471 -0.298493
             b    0.385795 -0.915417 -1.367644

and say that I have the following series s with two-levels as a multi-index (notice that it shares the first two levels):

              Flag
X      Y     
bar   one     True                 
baz   three  False
      two     True
      four    True
foo   one    False
qux   two     True

I would like to use s to populate df:

                   A         B         C            F
X      Y     Z                          
bar   one    a   -0.007381 -0.365315 -0.024817   True
             b   -1.219794  0.370955 -0.795125   True
baz   three  a    0.145578  1.428502 -0.408384  False
             b   -0.249321 -0.292967 -1.849202  False
      two    a   -0.249321 -0.292967 -1.849202   True
      four   a    0.21     -0.967123  1.202234   True
foo   one    b   -1.046479 -1.250595  0.781722  False
             a    1.314373  0.333150  0.133331  False
qux   two    c    0.716789  0.616471 -0.298493   True
             b    0.385795 -0.915417 -1.367645   True

How can I do that?

Upvotes: 1

Views: 108

Answers (1)

chrisb
chrisb

Reputation: 52286

This won't be particularly fast, may be something better available, but should work. See the docs on slicing MultiIndexes for a little more background.

idx = pd.IndexSlice
for (lvl1, lvl2), value in s.iteritems():
    df.loc[idx[lvl1, lvl2, :], 'Flag'] = value

Upvotes: 1

Related Questions