Home > Blockchain >  How add columns with variable and different names in pandas
How add columns with variable and different names in pandas

Time:07-23

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?

CodePudding user response:

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
  • Related