0

I have a simple pandas dataframe with a column 'mycol' and has 5 rows in it and I'm trying to create 5 new variables for every row value, something like below:

newcol_1=df['mycol'][0]
newcol_2=df['mycol'][1]
newcol_3=df['mycol'][2]
newcol_4=df['mycol'][3]
newcol_5=df['mycol'][4]

I don't want to hard code as above and I'm using the below "for loop" but it keeps throwing 'can't assign to operator'. I know that assignment values should be on the right and variable on the left but not sure how do I use for loop to dynamically create these 5 variables.

for i in 0, df.shape[0]-1:
    #"newcol_"+str(i+1) =df['mycol'][i]  # this isn't working
    newcol_+str(i+1) =df['mycol'][i]     # this also isn't working

Appreciate if anyone can help with this...Thanks!

Laurent
  • 12,287
  • 7
  • 21
  • 37

1 Answers1

1

Preferred option: modify globals()

# Create variables dynamically 
for i, value in enumerate(df["VALUE"].values):
    globals()[f"newcol_{i+1}"] = value
# Test that newcol_3 exists, for instance
print(newcol_3)  # Works fine
print(newcol_3 == df['mycol'][2])  # True

Alternate option: use exec()

Though one should do so with caution

# Create a new dict with desired key/value pairs
newcols = {f"newcol_{i+1}": value for i, value in enumerate(df["VALUE"].values)}

# Create new variables dynamically from dict
for name, value in newcols.items():
    exec(f"{name}= {value}")

# Previous tests work just as fine
Laurent
  • 12,287
  • 7
  • 21
  • 37
  • Thanks Laurent. You are close...But, what I want is these new 5 variables as newcol1, newcol2,...newcol5 and not as subscript like newcol[1],newcol[2]...newcol[5]. I'm creating these 5 variables as placeholders and will be passing onto my next program so don't want to create a list or dictionary of variables... – user11580242 Apr 30 '21 at 15:05
  • Thanks..it worked although it's little complex than I thought and also remember reading online about using "exec" cautiously. Anyway, for now, it works and if anyone has any other simple solution that would be great. – user11580242 Apr 30 '21 at 20:29
  • Great...Thank you for your personal attention and time. – user11580242 Apr 30 '21 at 20:56