I have a DataFrame with multiIndex columns. Suppose it is this:
index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),
('two', 'a'), ('two', 'b')])
df = pd.DataFrame({'col': np.arange(1.0, 5.0)}, index=index)
df = df.unstack(1)
(I know this definition could be more direct). I now want to set a new level 0 column based on a DataFrame. For example
df['col2'] = df['col'].applymap(lambda x: int(x < 3))
This does not work. The only method I have found so far is to add each column seperately: Pandas: add a column to a multiindex column dataframe , or some sort of convoluted joining process.
The desired result is a new level 0 column 'col2'
with two level 1 subcolumns: 'a'
and 'b'
Any help would be much appreciated, Thank you.