Supposing that I have a pandas multi level columns data-frame df like this:
| A | B -> first level
---------------------------------
| x y | x y -> second level
---------------------------------
0| 5 5 | 1 5
1| 3 1 | 4 7
2| 1 4 | 10 20
3| 50 8 | 7 8
How can I create a new column with the difference between x and y for each level?
I know that I could do one by one, like this:
df["A"]["diff"] = df["A"].x - df["A"].y
df["B"]["diff"] = df["B"].x - df["B"].y
The final output would be:
| A | B -> first level
-----------------------------------------------
| x y diff | x y diff -> second level
-----------------------------------------------
0| 5 5 0 | 1 5 -4
1| 3 1 2 | 4 7 -3
2| 1 4 -3 | 10 20 -10
3| 50 8 42 | 7 8 -1
Is there a one line operation to apply this column creation for all levels at once?
My solution this seems very repetitive, and in my case I may have several (more than 10 labels) at first level).
Is there a better way of doing it?