python多个excel文件合并
时间: 2023-07-11 21:09:01 浏览: 128
可以使用 pandas 库中的 read_excel() 和 concat() 方法来实现多个 Excel 文件的合并。
首先,使用 read_excel() 方法读取每个 Excel 文件,并将它们存储在一个列表中。例如:
```
import pandas as pd
# 读取第一个 Excel 文件
df1 = pd.read_excel('file1.xlsx')
# 读取第二个 Excel 文件
df2 = pd.read_excel('file2.xlsx')
# 将数据框存储在列表中
dfs = [df1, df2]
```
接下来,使用 concat() 方法将列表中的数据框合并成一个数据框。例如:
```
# 合并数据框
result = pd.concat(dfs)
# 将合并后的数据框保存为 Excel 文件
result.to_excel('merged.xlsx', index=False)
```
在这个例子中,我们将多个 Excel 文件合并成一个名为 merged.xlsx 的文件,并将它存储在当前工作目录中。
如果需要合并的 Excel 文件非常多,可以使用一个循环来自动读取每个文件并将它们添加到数据框列表中。例如:
```
import os
# 获取当前工作目录中所有 Excel 文件的文件名
files = os.listdir('.')
excel_files = [f for f in files if f.endswith('.xlsx')]
# 创建一个空的数据框列表
dfs = []
# 循环读取每个 Excel 文件并将其添加到数据框列表中
for f in excel_files:
df = pd.read_excel(f)
dfs.append(df)
# 合并数据框
result = pd.concat(dfs)
# 将合并后的数据框保存为 Excel 文件
result.to_excel('merged.xlsx', index=False)
```
这个例子中,我们首先使用 os.listdir() 方法获取当前工作目录中所有的 Excel 文件名,并将它们存储在一个列表中。然后,我们使用一个循环来读取每个 Excel 文件并将它们添加到数据框列表中。最后,我们将所有数据框合并成一个数据框,并将它保存为 merged.xlsx 文件。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)