Skip to content Skip to sidebar Skip to footer

Creating New Column Names From A List Of Strings In A Loop

Let us say I have the following column names in pandas: ['A', 'B'] My problem is that I want to use a for loop that grabs the column names from the list and creates a new column na

Solution 1:

You can use Series.apply in loop:

a = ["A", "B"]
for i in a:
    df[i + "_c"] =  df[i].apply(SOME FUNCTION) 

Or DataFrame.apply with add_suffix for new df and then join to original:

df1 = df[a].apply(SOME FUNCTION).add_suffix('_c')
df = df.join(df1)

Sample:

df = pd.DataFrame({'A':[4,5,4,5,5,4],
                   'B':[7,8,9,4,2,3],
                   'C':[1,3,5,7,1,0]})

print (df)
   A  B  C
0  4  7  1
1  5  8  3
2  4  9  5
3  5  4  7
4  5  2  1
5  4  3  0

def FUNCTION(x):
    return x + 10

a = ["A", "B"]

for i in a:
    df[i + "_c"] =  df[i].apply(FUNCTION) 

print (df)
   A  B  C  A_c  B_c
0  4  7  1   14   17
1  5  8  3   15   18
2  4  9  5   14   19
3  5  4  7   15   14
4  5  2  1   15   12
5  4  3  0   14   13

df = df.join(df[a].apply(FUNCTION).add_suffix('_c'))
print (df)
   A  B  C  A_c  B_c
0  4  7  1   14   17
1  5  8  3   15   18
2  4  9  5   14   19
3  5  4  7   15   14
4  5  2  1   15   12
5  4  3  0   14   13

Post a Comment for "Creating New Column Names From A List Of Strings In A Loop"