用python中pandas写一段合并excel表格的代码。要求:多个excel文件在同一个文件夹下,遍历文件夹,每个excel表格数据结构相同
时间: 2024-05-03 09:20:54 浏览: 10
好的,以下是代码示例:
```python
import os
import pandas as pd
# 设置文件夹路径和合并后的文件名
folder_path = './data/'
output_file = 'merged_data.xlsx'
# 获取文件夹中的所有excel文件
all_files = os.listdir(folder_path)
excel_files = [file for file in all_files if file.endswith('.xlsx')]
# 读取每个excel文件的数据到DataFrame中,并合并成一个大的DataFrame
merged_df = pd.concat([pd.read_excel(os.path.join(folder_path, file)) for file in excel_files])
# 将数据保存到合并后的excel文件中
merged_df.to_excel(output_file, index=False)
print('已将所有excel表格成功合并成一个文件!')
```
这段代码能够合并文件夹中的所有excel表格,每个表格的数据结构相同。请将代码中的文件夹路径和输出文件名修改为你自己的路径和文件名,然后运行代码即可。