0

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?

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
hov11235
  • 3
  • 2

1 Answers1

1

Just use a dict.

data = {}
for v in ["A", "B"]:
    a, b = df.groupby("C")[v]
    data[v] = (a[1], b[1])

EDIT: as discussed in the comments, to create keys V_0 and V_1,

data = {}
for v in ["A", "B"]:
    a, b = df.groupby("C")[v]
    data[f"{v}_0"] = a[1]
    data[f"{v}_1"] = b[1]
AKX
  • 152,115
  • 15
  • 115
  • 172
  • Thank you for the answer. This does create a dictionary with the columns I need, however the variable names are not what I need. I oversimplified the actual situation. Normally I need to use this with a much larger dataframe, so the part where the new variable names are some modification of the existing variable names is extremely important. any suggestion on that? – hov11235 Apr 03 '20 at 08:57
  • If you want an answer to your actual question and not a simplification, you shouldn't omit those details! Either way, this will result in a dict where the keys are the same `A` and `B` as in your "variables" above, so I'm not sure what the problem is. – AKX Apr 03 '20 at 09:20
  • Well, now that i think about it, it doesn't matter how large the data is, so the simple question is just fine. Thank you for the answer again but it doesn't create keys `A_0 ` and `A_1` or `B_0` and `B_1` as my question (and its title) clearly specifies. – hov11235 Apr 03 '20 at 09:25
  • @hov11235 Well, sure. It's a trivial change; added an edit. – AKX Apr 03 '20 at 10:29
  • Thank you, this is a great solution – hov11235 Apr 03 '20 at 16:41