合并多个sheet的数据
对于某些固定列的数据,分布一个工作簿的多个sheets里面,有时候想要将它组合起来分析,而仅有的阻碍就是它分布在多个sheet里面,如果只有一两个sheet还好,可以通过复制粘贴的方式,但sheet过多,这种方式效率非常低下,同时容易出错。
结合数据处理的三方库pandas, 可以让这样的需求得到一种简单的处理方式。
先来一份测试数据:三个sheet的数据列名相同
; 合并多个sheet实现的思路:
对于一个Excel工作簿,重要点就在于循环读取多个sheet,获取各个sheet的值,将他们组合起来
1.读取文件
2.循环读取sheet,写入list
3.将list 的数据contact
4.将合并后的数据输出保存为一个新的表
合并多个sheet具体的实现:
import pandas as pd
import time
file_name = 'test_name1.xlsx'
df = pd.read_excel(file_name, None, index_col=0)
sheet_name_list = list(df.keys())
new_list = []
for name in sheet_name_list:
current_sheet = df[name]
new_list.append(current_sheet)
concat_data = pd.concat(new_list)
new_name = str(int(time.time())) + '.xlsx'
concat_data.to_excel(new_name)
print('Finish!',new_name)
合并后的结果
这是合并后生成新文件的更好方法。没有对源数据进行任何更改。合并文件的输出如下所示:
[En]
It is a better way to generate a new file after merging. No changes have been made to the source data. The output of the merged file is as follows:
; 合并多个工作簿
这是一种合并的场景,另外,有时候我们还会遇到另外一种场景。
同样是一个工作簿存在多个sheet,每个sheet的列名相同,但这样的工作簿有多个,预期是想要将存在多个sheets的多个工作簿合并到一个里面
简单模拟一个测试的数据:
合并多个工作簿的实现思路:
在原有的一个工作簿多个sheet的基础上,增加了一个具有同样列名的工作簿
1.遍历所有的工作簿
2.再遍历单个工作簿下的sheet
3.写入sheet和输出,和前面的实现都是类似的
比较巧妙的处理是,既然列名相同,不管有多少个工作簿,我只需要将sheet读取出来,存入一个list,合并输出即可。
合并多个工作簿具体的实现:
import pandas as pd
import time
import os
new_list = []
file_path = 'test_data/'
file_list = os.listdir(file_path)
print('all file:', file_list)
for file in file_list:
if not file.startswith('.'):
df = pd.read_excel(file_path + file, None, index_col=0)
sheet_names = list(df.keys())
for name in sheet_names:
current_sheet = df[name]
new_list.append(current_sheet)
new_df = pd.concat(new_list)
new_name = str(int(time.time())) + '.xlsx'
new_df.to_excel(file_path + new_name)
合并的结果展示:
您可以看到合并的结果,正如我们所预期的那样,这两个工作簿已成功合并为一个工作簿并作为新文件输出。
[En]
You can see the result of the merge, and as we expected, the two workbooks were successfully merged into one and output as a new file.
其实,分析这两个场景,思路是相似的,实现方式都是增加一个额外的循环,遍历文件。
[En]
In fact, the analysis of these two scenarios, the idea is similar, the way of implementation is to add an extra loop, traversing the file.
当然,这中合并只适用于各个工作簿以及各个sheet列名相同的情况,其他一些更加复杂的合并,可能要根据情况进行调整
比如如果数据中出现空行或者未命名的列,要进行特殊处理
new_data=df_concat.loc[:,~df_concat.columns.str.contains("^Unnamed")]
new_=new_data.dropna(how='all')
有问题随时可私信,一起交流探讨
如果对你有帮助,可以请博主咖啡哟~~ ☕️
Original: https://blog.csdn.net/weixin_43643587/article/details/121366852
Author: Richard.sysout
Title: 合并Excel工作簿、合并多个sheet的基本实现:

pytorch和tensorflow函数对应关系(持续更新)

python-函数与 Lambda 表达式

sagemaker在终端节点部署Tensorflow模型并调用

注意力机制

Windows安装GPU版本的tensorflow+CUDA+CUDNN(超详细)

《Few-Shot Named Entity Recognition: A Comprehensive Study》论文笔记

【案例】聚类算法

华为HCIP-AI认证题库中的部分问题

语音识别之HTK入门

【Tensorflow2.x学习笔记】- Keras高层接口

CVPR2022知识蒸馏用于目标检测:Focal and Global Knowledge Distillation for Detectors

R2CNN模型——用于文本目标检测的模型

GANs系列:DCGAN原理简介与基础GAN的区别对比

【Bert + BiLSTM + CRF】实现实体命名识别,后续封装Dataset,DataLoader,进行批次训练
