Home > database >  Create a new column in multiple dataframes using for loop
Create a new column in multiple dataframes using for loop

Time:11-17

I have multiple dataframes with the same structure but different values for instance,

df0, df1, df2...., df9

To each dataframe I want to add a column named eventdate that consists of one date, for instance, 2019-09-15 using for loop

for i in range(0, 9);
    df str(i)['eventdate'] = "2021-09-15"

but I get an error message SyntaxError: cannot assign to operator

I think it's because df isn't defined. This should be very simple.. Any idea how to do this? thanks.

CodePudding user response:

dfs = [df0, df1, df2...., df9]
dfs_new = []

for i, df in enumerate(dfs):
    df['eventdate'] = "2021-09-15"
    dfs_new.append(df)

if you can't generate a list then you could use eval(f"df{str(num)}") but this method isn't recommended from what I've seen

  • Related