convert a dictionary of pandas date frame into one excel file with different sheets

Question:

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

Asked By: user20309717

||

Answers:

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.

Answered By: Arnau

Pandas has a built-in to_excel() function:

df.to_excel()

And, per their documentation, you can define an ExcelWriter that writes to multiple sheets.

To write a single object to an Excel .xlsx file it is only necessary to
specify a target file name. To write to multiple sheets it is necessary to
create an ExcelWriter object with a target file name, and specify a sheet
in the file to write to.

Multiple sheets may be written to by specifying unique sheet_name.
With all data written to the file it is necessary to save the changes.
Note that creating an ExcelWriter object with a file name that already
exists will result in the contents of the existing file being erased.

You end with something like this (updated with Arnau’s iterator, but follows the docs):

with pd.ExcelWriter('output.xlsx') as writer:
    for k in df_dict:
        df_dict[k].to_excel(writer, sheet_name=k)
Answered By: lil-solbs
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.