Reputation: 1
I have a list of dataframes (df_names). I would like to convert it into the df_list. This is because I would like to create a for loop (shown at the bottom) which adds a column to each data frame and places the corresponding value/name in df_names in that column.
I've tried to remove the quotes from df_names to create df_list however, the for loop is still treating it as a list/str not as a tuple containing the data frames.
To summarise, I just want to convert the list df_names into a tuple to run the for loop below.
...
df_names = ['df1', 'df2', 'df3']
df_list = [df1, df2, df3]
for i, k in zip(df_list, df_names):
i['new_column'] = k
...
Upvotes: 0
Views: 62
Reputation: 4860
This works, but I wouldn't recommend it. You should really just store your dataframes in a dict
.
df_names = ['df1', 'df2', 'df3']
# Assuming df1, df2, and df3 are defined previously
df_list = [globals()[name] for name in df_names]
for i, k in zip(df_list, df_names):
i['new_column'] = k
globals()
returns the dictionary implementing the current module namespace. For code within functions, this is set when the function is defined and remains the same regardless of where the function is called.
locals()
returns a dictionary representing the current local symbol table. Free variables are returned by locals()
when it is called in function blocks, but not in class blocks. Note that at the module level, locals()
and globals()
are the same dictionary.
Upvotes: 0