'using vars() inside a python function?

I was performing some operations (successfully) outside of a function:

x = df.copy
do stuff to get df1 and df2 
for f in ['df1','df2']:
   do stuff
   vars()[f] = stuff

This works fine. And the only reason I'm using vars() here is because it's the only way I can figure out how to save each dataframe simply after looping since 'f = stuff' won't save the result to the original dataframe. But whenever I throw this in a function, it seems to break. The variable doesn't save ie df1 remains the same state it was before the for-loop. Any advice?

def func (df):
   x = df.copy
   do stuff to get df1 and df2 
   for f in ['df1','df2']:
      do stuff
      vars()[f] = stuff
   df = pd.concat((df1,df2),axis=0)
   return df


Solution 1:[1]

There's no need to assign the dataframes to variables. Just put them in a list, and pass that to pd.concat().

def func (df):
   x = df.copy
   do stuff to get df1 and df2 
   df_list = []
   for f in ['df1','df2']:
      do stuff
      df_list.append(stuff)
   df = pd.concat(df_list,axis=0)
   return df

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar