How add columns with variable and different names in pandas

Question:

Suppose I have a dataframe in pandas, e.g.

import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9]})

I want to add new columns dynamically with names depending on the current iteration.
I tried

for k in range(2):
   column_name = 'new_column_' + str(k)
   df = df.assign(column_name=[0,0,0])

As output, I expected

   A  B  C  new_column_0  new_column_1
0  1  4  7             0             0
1  2  5  8             0             0
2  3  6  9             0             0

Unfortunately, only one column is created with the name ‘column_name’.

How can I dynamically add columns with names determined by variables?

Asked By: Butters

||

Answers:

You cau use pandas.assign like below.

df = df.assign(**{f'new_column_{k}' : 0 for k in range(2)})
print(df)

   A  B  C  new_column_0  new_column_1
0  1  4  7             0             0
1  2  5  8             0             0
2  3  6  9             0             0
Answered By: I'mahdi
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.