0

I have a dataframe in python, called df. It contains two variables, Name and Age. I want to do a loop in python to generate 10 new column dataframes, called Age_1, Age_2, Age_3....Age_10 which contain the values of Age.

So far I have tried:

import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])
for i in range(1,11):
     df[Age_'i'] = df['Age']
Alex
  • 29
  • 1
  • 6
  • 3
    `df[f'Age_{i}'] = `: https://stackoverflow.com/questions/2960772/how-do-i-put-a-variable-inside-a-string. But are you really just looking to repeat that column 10 times? – ALollz Apr 12 '21 at 15:50

2 Answers2

1

Just use this for loop:

for x in range(0,11):
    df['Age_'+str(x)]=df['Age']

OR

for x in range(0,11):
    df['Age_{}'.format(x)]=df['Age']

OR

for x in range(0,11):
    df['Age_%s'%(x)]=df['Age']

Now if you print df you will get your desired output:

enter image description here

Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
1

you can use .assign and ** unpacking.

df.assign(**{f'Age_{i}' : df['Age'] for i in range(11)})

enter image description here

Umar.H
  • 22,559
  • 7
  • 39
  • 74