Reputation: 1471
First of all, I wrote this function:
def writing_in_excel(path, df, sheet_name):
writer = pd.ExcelWriter(path, datetime_format='m/d/yyyy')
df.to_excel(writer, sheet_name = sheet_name, index=False, freeze_panes = (0,1))
writer.save()
writer.close()
Then, I have a dictionary of dataframes:
import pandas as pd
employee = {'EmployeeID' : [0,1,2,3,4,5,6,7,8,9],
'FirstName' : ['a','b','c','d','e','f','g','h','i','j'],
'LastName' : ['a','b','c','d','e','f','g','h','i','j'],
'favorite_color' : ['red','blue','green','yellow','red','red','green','blue','green','red']}
df = pd.DataFrame(employee)
by_color_df_dict = dict(tuple(df.groupby('favorite_color')))))
In 'favorite_color', there are 4 different values, I wanted to create separate dataframes by the 4 values in 'favorite_color'
If you run that code, you will get a dictionary of dataframes as a result. I want to loop through the dictionary and save each dataframes as an excelfile using the function that I defined above.
I think I have to start with:
for key, value in by_color_df_dict:
but I can not proceed further with my shallow knowledge.
Please help me with this.
Upvotes: 1
Views: 1900
Reputation: 3232
You can just do
for color_name, group in df.groupby('favorite_color'):
writing_in_excel('file_name.xlsx', group, color_name)
Upvotes: 4