Home > Enterprise >  Name columns created in for-loop
Name columns created in for-loop

Time:09-30

I'm inserting new columns with a for-loop in same amount as already existing columns in pandas dataframe (making coulmns x2 as many). I get the correct amount of new columns with below loop, but they are named 1 through 3 (amount of primary columns)

However, I want a word in front of these numbers. e.g. "hi"

for i in range(1,len(df.columns) 1):
    df[i] =  0
    print(i)

I get:

Primary Col 1 Primary Col 2 Primary Col 3 1 2 3
a a a 0 0 0
a a a 0 0 0

I want:

Primary Col 1 Primary Col 2 Primary Col 3 hi1 hi2 hi3
a a a 0 0 0
a a a 0 0 0

Anyone wish to help me?

CodePudding user response:

The answer is stated by @BigBen above. Thanks!

for i in range(1,len(df.columns) 1):
    df['hi'   str(i)] = 0
    print(i)

CodePudding user response:

As @BigBen commented, you can directly concatenate a string in the for loop:

for i in range(1,len(df.columns) 1):
    df['hi'   str(i)] =  0
    print(i)

You might also concatenate variables or use f-strings e.g.

foo = "Hi"
for i in range(1,len(df.columns) 1):
    df[foo   str(i)] =  0
    print(i)

With f-strings:

foo = "Again"
for i in range(1,len(df.columns) 1):
    df[f'Hi_{foo}'  str(i)] =  0
    print(i)
  • Related