Given df 'AB':
A = pd.DataFrame([[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]],
columns=['A', 'B', 'C'], index=[1, 2, 3, 4, 5])
B = pd.DataFrame([[3, 3, 3], [2, 2, 2], [4, 4, 4], [5, 5, 5], [6, 6, 6]],
columns=['A', 'B', 'C'], index=[1, 2, 3, 4, 5])
A.columns = pd.MultiIndex.from_product([['A'], A.columns])
B.columns = pd.MultiIndex.from_product([['B'], B.columns])
AB = pd.concat([A, B], axis = 1)
I would like to add a column 'new' to the level 'B', based on a condition of column ['B', 'C']. I'm looking to specifically use df.loc, like this:
AB['B', 'new'] = 0
AB.loc[AB['B', 'C'] >= 3, 'new'] = 1
The problem is that this procedure creates a 'new' df instead of filling the column ['B', 'new'].
The desired output is:
A B
A B C A B C new
1 1 5 2 3 3 3 1
2 2 4 4 2 2 2 0
3 3 3 1 4 4 4 1
4 4 2 2 5 5 5 1
5 5 1 4 6 6 6 1