I would like to add a new level to my DF (so that then I can use pd.reindex
to do something else). My DF basically has something like this:
df = pd.DataFrame({('A','a'): [-1,-1,0,10,12],
('A','b'): [0,1,2,3,-1],
('A','c'): [-1,1,0,10,12],
('A','d'): [1,1,2,3,-1],
('B','a'): [-20,-10,0,10,20],
('B','b'): [-200,-100,0,-1,200],
('B','c'): [-20,-10,0,10,20],
('B','d'): [-200,-100,0,100,200]
})
##df
A B
a b c d a b c d
0 -1 0 1 1 -20 -200 -20 -200
1 -1 1 -1 1 -10 -100 -10 -100
2 0 2 0 2 0 0 0 0
3 10 3 10 3 10 -1 10 100
4 12 -1 12 -1 20 200 20 200
I want to assign new level keys L1
= a
+b
, and L2
=c
+d
. How do I do this?
The desired output would be
##df
A B
L1 L2 L1 L2
a b c d a b c d
0 -1 0 1 1 -20 -200 -20 -200
1 -1 1 -1 1 -10 -100 -10 -100
2 0 2 0 2 0 0 0 0
3 10 3 10 3 10 -1 10 100
4 12 -1 12 -1 20 200 20 200
Edit: the objective is to achieve something similar to what was asked in here. This means that some rows will have NA
s for the same KEY, depending on the value of other columns.
E.g. if I want to filter columns a
and c
by respectively testing whether columns b
and d
are negative:
##df
A B
L1 L2 L1 L2
a b c d a b c d
0 -1 0 1 1 NA NA NA NA
1 -1 1 -1 1 NA NA NA NA
2 0 2 0 2 0 0 0 0
3 10 3 10 3 NA NA 10 100
4 NA NA NA NA 20 200 20 200