python合并excel
时间: 2023-09-05 08:13:40 浏览: 98
可以使用Python的pandas库来合并Excel文件。
首先,需要安装pandas库。可以使用以下命令在终端中安装:
```
pip install pandas
```
然后,可以使用pandas库中的read_excel()函数读取Excel文件,并使用concat()函数将多个Excel文件合并成一个DataFrame。例如:
``` python
import pandas as pd
# 读取第一个Excel文件
df1 = pd.read_excel('file1.xlsx')
# 读取第二个Excel文件
df2 = pd.read_excel('file2.xlsx')
# 合并两个DataFrame
result = pd.concat([df1, df2])
# 将合并后的DataFrame保存为新的Excel文件
result.to_excel('merged.xlsx', index=False)
```
在上面的代码中,read_excel()函数用于读取Excel文件,concat()函数用于将两个DataFrame合并成一个,to_excel()函数用于将合并后的DataFrame保存为一个新的Excel文件。其中,index=False参数表示不保存行索引。
如果需要合并多个Excel文件,可以使用循环读取每个文件,并将它们合并到一个列表中,然后使用concat()函数合并整个列表。例如:
``` python
import pandas as pd
import glob
# 读取所有Excel文件
all_files = glob.glob('*.xlsx')
# 将所有Excel文件合并成一个DataFrame
li = []
for filename in all_files:
df = pd.read_excel(filename, index_col=None, header=0)
li.append(df)
result = pd.concat(li, axis=0, ignore_index=True)
# 将合并后的DataFrame保存为新的Excel文件
result.to_excel('merged.xlsx', index=False)
```
在上面的代码中,glob()函数用于获取所有Excel文件的文件名,循环读取每个文件,并将它们合并到一个列表中,最后使用concat()函数将整个列表合并成一个DataFrame。其中,axis=0参数表示按行合并,ignore_index=True参数表示忽略原始的行索引。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.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)
![](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://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)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)