python - Assigning values to Pandas Multiindex DataFrame by index level -


i have pandas multiindex dataframe , need assign values 1 of columns series. series shares index first level of index of dataframe.

import pandas pd import numpy np idx0 = np.array(['bar', 'bar', 'bar', 'baz', 'foo', 'foo']) idx1 = np.array(['one', 'two', 'three', 'one', 'one', 'two']) df = pd.dataframe(index = [idx0, idx1], columns = ['a', 'b']) s = pd.series([true, false, true],index = np.unique(idx0)) print df print s 

out:

                b bar 1    nan  nan     2    nan  nan     3  nan  nan baz 1    nan  nan foo 1    nan  nan     2    nan  nan  bar     true baz    false foo     true dtype: bool 

these don't work:

df.a = s # not raise error, nothing df.loc[s.index,'a'] = s # raises error 

expected output:

                 b bar 1    true   nan     2    true   nan     3  true   nan baz 1    false  nan foo 1    true   nan     2    true   nan 

series (and dictionaries) can used functions map , apply (thanks @normanius improving syntax):

df['a'] = pd.series(df.index.get_level_values(0)).map(s).values 

or similarly:

df['a'] = df.reset_index(level=0)['level_0'].map(s).values 

results:

a    b bar 1     true  nan     2     true  nan     3   true  nan baz 1    false  nan foo 1     true  nan     2     true  nan 

Comments