I have multiple dataframes and for each of them I am creating a separate excel sheet. After I've done this, I want to add for each sheet the sum of a certain column.
I have tried to create a dictionary and in the for loop when I create the dataframes to add to the dictionary the name of the excel sheet and the sum of the column that I want. Here is an example of what I have done :
for p in my_list:
total = {}
...
df[p] = pd.Dataframe(my_list)
total[p] = df[p]['column'].sum()
.....
sheet['D32'] = total.get(sheet_name)
When i do this the total dictionary keeps updating at each iteration and in the end for each sheet in my excel file I get the same value corresponding to the last dataframe. Could you help me with a solution?
You are initialising total
inside the loop so it gets reinitialised at each iteration. Initialise it before the loop:
total = {}
for p in my_list:
...
df[p] = pd.Dataframe(my_list)
total[p] = df[p]['column'].sum()
.....
sheet['D32'] = total.get(sheet_name)