I have a DataFrame (call it df) object with columns named A, B, and C where C is a binary variable. I am trying to create new variables A_1, A_0, B_1, and B_0 in a loop. These variables are created according to the value of C. For example A_0 is the portion of my original column A where the corresponding value of C is 0.
The following code does what I need:
variables=list('A', 'B')
for v in variables:
exec(f'{v}_0, {v}_1 = df.groupby("C")["{v}"]') #this returns a tuple
exec(f'{v}_0, {v}_1 = {v}_0[1], {v}_1[1]') #this returns what i need
It's clumsy, and, as far as I know, exec()
is a bad practice. Is there a better way do this?