I have a dictionary where the keys are names of pandas data frames and the items are the data frames themselves. I want to save this file into an excel file with different sheets, where the name of each sheet is one key of the dictionary and the data inside the sheet is the item (data frame) corresponding to that key.
So let say the dictionary is dict = {df_1: dataframe_1, df_2: dataframe_2, ...}, I want to convert this into one excel file with sheet one name is df_1 and the data inside is dataframe_1, etc.
Any help is appreciated.
Thanks
>Solution :
The pandas.DataFrame.to_excel function provides the parameter sheet_name which can be used to specify the name of the excel sheet in which the dataframe is to be written. Use
with pd.ExcelWriter('output.xlsx') as writer:
for k in df_dict:
df_dict[k].to_excel(writer, sheet_name=k)
Note that it is better to use an pd.ExcelWriter here to avoid opening and closing the file unnescessarily.