python 同一工作簿中多个Sheet合并
时间: 2023-12-07 11:05:09 浏览: 168
可以使用 pandas 库来合并同一工作簿中的多个 sheet。
以下是示例代码:
```python
import pandas as pd
# 读取工作簿中的多个 sheet
sheet1 = pd.read_excel('workbook.xlsx', sheet_name='Sheet1')
sheet2 = pd.read_excel('workbook.xlsx', sheet_name='Sheet2')
sheet3 = pd.read_excel('workbook.xlsx', sheet_name='Sheet3')
# 合并多个 sheet
merged_sheet = pd.concat([sheet1, sheet2, sheet3], ignore_index=True)
# 将结果写入新的 sheet
with pd.ExcelWriter('workbook.xlsx') as writer:
merged_sheet.to_excel(writer, sheet_name='Merged')
```
以上代码将读取名为 `workbook.xlsx` 的工作簿中的三个 sheet,并将它们合并为一个数据框。然后,将合并的数据框写入名为 `Merged` 的新 sheet 中。
相关问题
python excel合并列
### 使用 Python Pandas 合并 Excel 文件中的多列
当处理多个 Excel 表格并将特定列合并到一个新的数据帧中时,Pandas 提供了强大的工具来简化这一过程。下面是一个详细的例子说明如何实现这一点。
首先安装所需的库:
```bash
pip install pandas openpyxl
```
读取多个 Excel 文件,并指定要从中提取的列名列表。假设这些文件位于同一目录下并且具有相同的结构:
```python
import os
import pandas as pd
# 定义路径和感兴趣的列名称
path = './excels/' # 存放Excel文件夹的位置
columns_of_interest = ['A', 'B'] # 需要保留下来的列名
all_files = [f for f in os.listdir(path) if f.endswith('.xlsx')]
dfs = []
for filename in all_files:
df = pd.read_excel(os.path.join(path, filename), usecols=columns_of_interest)
dfs.append(df)
combined_df = pd.concat(dfs, ignore_index=True)
print(combined_df.head())
```
上述脚本会遍历给定路径下的所有 `.xlsx` 文件,只选取定义好的几列(这里是以 `['A','B']`为例),最后通过 `pd.concat()` 函数将它们垂直堆叠起来形成新的 DataFrame[^1]。
如果目标是从单个工作簿内的不同工作表中获取不同的列,则可以根据需求调整代码逻辑如下所示:
```python
file_path = './example.xlsx' # 单一Excel文件位置
sheets_to_read = ['Sheet1', 'Sheet2']
dataframes_list = []
with pd.ExcelFile(file_path) as xls:
for sheet_name in sheets_to_read:
temp_df = pd.read_excel(xls, sheet_name=sheet_name)
relevant_columns = list(set(temp_df.columns).intersection(columns_of_interest))
filtered_df = temp_df[relevant_columns]
dataframes_list.append(filtered_df)
final_combined_df = pd.concat(dataframes_list, axis=0, ignore_index=True)
print(final_combined_df.head())
```
这段代码展示了从同一个 Excel 文件的不同工作表里挑选所需列的方式。注意这里的 `axis=0` 参数表示沿行方向连接 DataFrames;而设置 `ignore_index=True` 可以重新创建索引以便更好地管理新组合的数据集。
pandas如何依次将同一个工作簿下的多个相同字段名的工作表内容存入DataFrame
可以使用 pandas 的 `read_excel()` 函数结合循环读取同一工作簿下的多个相同字段名的工作表内容,并将它们存入同一个 DataFrame 中。具体步骤如下:
1. 导入 pandas 模块:
```python
import pandas as pd
```
2. 使用 `ExcelFile()` 函数打开 Excel 文件并获取工作簿对象:
```python
xls = pd.ExcelFile('example.xlsx')
```
3. 获取工作簿中所有的工作表名:
```python
sheet_names = xls.sheet_names
```
4. 使用循环读取每个工作表中的数据,并将它们存入同一个 DataFrame 中:
```python
df = pd.DataFrame()
for sheet_name in sheet_names:
data = pd.read_excel(xls, sheet_name=sheet_name)
df = pd.concat([df, data], ignore_index=True)
```
上述代码中,通过 `pd.concat()` 函数将每个工作表中的数据按行合并到同一个 DataFrame 中,并使用 `ignore_index=True` 参数重新设置 DataFrame 的索引。
将上述代码中的 Excel 文件名和字段名改为实际的文件名和字段名即可运行。
阅读全文
相关推荐














