Home >Backend Development >Python Tutorial >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:
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!