python - 将多个 Excel 工作表合并为一个 Excel 工作表
问题描述
我有一个文件夹,我有 3 个 excel 文件,M、N、P 和 M、N、P 三张表 one_、two_ 和three_
Main
|
|_M.xlsx
| |_ one_M.xlsx
| |_ two_M.xlsx
| |_ three_M.xlsx
| |_f_M.xlsx
| |_O.M.xlsx
|_N.xlsx
| |_ one_N.xlsx
| |_ two_N.xlsx
| |_ three_N.xlsx
| |_f_M.xlsx
| |_O.M.xlsx
|_P.xlsx
|_ one_P.xlsx
|_ two_P.xlsx
|_ three_P.xlsx
|_f_M.xlsx
|_O.M.xlsx
我想要一个这样的合并后的excel文件
Main
|
|_Main.xlsx
|_ one_M.xlsx
|_ two_M.xlsx
|_ three_M.xlsx
|_ one_N.xlsx
|_ two_N.xlsx
|_ three_N.xlsx
|_ one_P.xlsx
|_ two_P.xlsx
|_ three_P.xlsx'
我怎样才能使用熊猫做到这一点
解决方案
如果您使用sheet_name=None
in pd.read_excel
,您可以一次读取工作簿中的所有工作表。它们将与数据框合并到有序字典中。键将作为工作表的名称。
试试这个代码:
df = pd.concat(pd.read_excel(workbook_path, sheet_name=None), ignore_index=True)
如果您只想将工作表合并到一个文件中:
paths_list=['path1', 'path2',...]
with pd.ExcelWriter('output_file_path.xlsx') as wr:
For path in paths_list:
df=pd.read_excel(path, sheet_name =None)
[df[sheetName].to_excel(wr, sheet_name=sheetName) for sheetName in df]
推荐阅读
- python - 如何为请求库创建嵌套参数
- vue.js - 在 Sidekick 中扫描后,无法在 iOS 上的 Nativescript Preview 中预览
- django - Django:默认将用户名保存在表单中
- docker - 在主机上运行 ELK stack docker
- javascript - 关闭离子页面并到达上一页,构造函数不起作用
- python - 在 keras 中使用生成器为 LSTM 模型提供序列
- apache-kafka - Kafka集群多节点配置
- ios - 客户端中的 Flutter HTTPS 握手错误(操作系统错误:CERTIFICATE_VERIFY_FAILED:ok(handshake.cc:363))
- install4j - 重新选择组件时不更新文件关联屏幕
- apache-flink - Flink - timesOrMore 的行为