Name columns created in for-loop

Question:

I’m inserting new columns with a for-loop in same amount as already existing columns in pandas dataframe (making columns x2 as many). I get the correct number of new columns with below loop, but they are named 1 through 3 (number 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?

Asked By: geaa

||

Answers:

The answer is stated by @BigBen above.
Thanks!

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

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)
Answered By: Adam
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.