Home > OS >  Storing Dataframes from a for loop into a list
Storing Dataframes from a for loop into a list

Time:06-30

df_list=[] #List of dataframes

for x in range(bin):
   df["Bin"] = pd.cut(df["Step"].astype(float), x)
   print(df) #returns 5 dataframes with different df['Bin'] columns
   df_list.append(df)

print(df_list)   

What I want is to store all 5 instances of the df created in the loop into the df_list but I seem to only get the last instance created 5 times. However when I print df inside of the loop I get all 5 data frames with the different columns.

How do I make sure to store all 5 instances created in the loop into the list and not just the last one?

CodePudding user response:

You are mutating (overwriting) the column df["Bin"] with each iteration of the for loop. Try this to save a copy of the dataframe instead.

df_list=[] #List of dataframes

for x in range(bin):
   df["Bin"] = pd.cut(df["Step"].astype(float), x)
   print(df) #returns 5 dataframes with different df['Bin'] columns
   df_list.append(df.copy())

print(df_list)   
  • Related