Home >Backend Development >Python Tutorial >How to Merge Multiple Pandas DataFrames from a For Loop into a Single Excel File?

How to Merge Multiple Pandas DataFrames from a For Loop into a Single Excel File?

Barbara Streisand
Barbara StreisandOriginal
2024-10-29 14:04:02916browse

How to Merge Multiple Pandas DataFrames from a For Loop into a Single Excel File?

Appending Pandas Dataframes Resulting from For Loop Iteration

In a recent programming task, a user encounters a challenge: accessing multiple Excel files through a for loop, reading their data into separate pandas dataframes, and subsequently merging these dataframes to save them as a single, comprehensive Excel file.

To begin, the user employs glob.glob to retrieve a list of Excel files within the operating directory. They then process each file using pandas.read_excel to obtain individual dataframes. However, the user experiences difficulty in appending these dataframes together for export.

An initial attempt involves using DataFrame.append(), but this method requires at least two dataframes as input. To overcome this, the user is advised to take the following steps:

  • Initialize an empty list, appended_data, to store the resulting dataframes.
  • Within the for loop, read each Excel file into a dataframe, data, and append it to the appended_data list.
  • After the loop completes, use pd.concat to merge all the dataframes in the appended_data list into a single dataframe, appended_data.
  • Finally, the user can export appended_data as an Excel file using to_excel.

Here's the revised code:

<code class="python">appended_data = []
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    appended_data.append(data)
appended_data = pd.concat(appended_data)
appended_data.to_excel('appended.xlsx')</code>

This solution provides a concise and straightforward method for appending multiple pandas dataframes generated from a for loop, allowing the user to save the consolidated data as a single Excel file.

The above is the detailed content of How to Merge Multiple Pandas DataFrames from a For Loop into a Single Excel File?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn