Assignments on new MultiIndex columns given only level 0 column selectors and aligned level 1

36 Views Asked by At

I would like to add a column to the level(0) of a multiindex column dataframe that has the same structure as the other columns, ie: the level(1) index is the same:

In [151]: df
Out[151]: 
first        bar                 baz           
second       one       two       one       two 
A       0.487880 -0.487661 -1.030176  0.100813 
B       0.267913  1.918923  0.132791  0.178503
C       1.550526 -0.312235 -1.177689 -0.081596 

Although I can do normal operations and get a single level column index dataframe aligned with the df's level(1):

In [152]: df['bar'] - df['baz']

I can't do a normal column assignment level(0) to create that level(0) column whose level(1) is populated by that of the resulting (aligned) dataframe:

In [153]: df['foo'] = df['bar'] - df['baz']

How is this done?

1

There are 1 best solutions below

0
On

I think we need to create the multiple index in the result then join it back

s = df['bar'] - df['baz']
s.columns = pd.MultiIndex.from_product([['foo'],s.columns])
df = df.join(s)
df
             bar                 baz                 foo          
             one       two       one       two       one       two
second                                                            
A       0.487880 -0.487661 -1.030176  0.100813  1.518056 -0.588474
B       0.267913  1.918923  0.132791  0.178503  0.135122  1.740420
C       1.550526 -0.312235 -1.177689 -0.081596  2.728215 -0.230639