python合并excel

0 思路

注意:此代码1,2是将多个excel合并到一个excel,3是根据某个键进行合并,针对键的合并需要使用merge函数,实现excel的vlookup功能

主要使用pandas操作excel,然后写入excel表

  1. pandas读取excel后数据类型是pd.DataFrame

  2. 将循环遍历的表都添加到一个DataFrame中

  3. 然后保存到excel

1. 多个文件读取合并

python 复制代码
'''
author : SnowMaple
time : 2023/11/30 9:24
'''

import pandas as pd 
import os import re # 用于存储所有要合并的Excel文件的文件名 

excel_files = ["1.xlsx", "2.xlsx", "3.xlsx","5.xlsx","6.xlsx"] # 创建一个用于存储所有数据的 combined_data = pd.DataFrame() # 逐个读取每个Excel文件的第一个sheet并合并 
for file in excel_files: 
    if os.path.isfile(file): # 确保文件存在 
        df = pd.read_excel(file, sheet_name=0) # 读取第一个sheet
        combined_data = combined_data.append(df, ignore_index=True) # 创建一个新的Excel文件来保存合并后的数据 
output_file = "combined_data3.xlsx"
combined_data.to_excel(output_file, index=False) 
print(f"合并后的数据已保存到 {output_file}")

2. 遍历文件夹读取

python 复制代码
'''
author : SnowMaple
time : 2023/11/30 9:24
'''

import pandas as pd
import os
import re

# 用于存储所有要合并的Excel文件的文件名

pattern = re.compile(r"^\d")
# 创建一个用于存储所有数据的DataFrame
folder_path = "C:/kaggle_data/titanic"
combined_data = pd.DataFrame()
for filename in os.listdir(folder_path):
    if filename.endswith(".xlsx") and pattern.search(filename):
        print(filename)
        df = pd.read_excel(filename, sheet_name=0)  # 读取第一个sheet
        combined_data = combined_data.append(df, ignore_index=True)
        

# 创建一个新的Excel文件来保存合并后的数据
output_file = "combined_data3.xlsx"
combined_data.to_excel(output_file, index=False)

print(f"合并后的数据已保存到 {output_file}")

3. 实现vlookup功能

根据某个键合并

python 复制代码
'''
author : SnowMaple
time : 2023/11/30
'''

import pandas as pd
# 1. 读数据
A = pd.read_excel('.\厦门XXXXX有限公司_20230XXXXX3351.xlsx') 
#也可指定列名 converters={"列名1":str, "列名2":str}
B = pd.read_excel('.\XXXXX明细.xlsx')

# 2. 数据预处理:注意A表和B表指定合并的键要一致
B= B.rename(columns={"号码":"serial_number"})

# 3. 合并 写入excel中
df = pd.merge(left=A, right=B, on="serial_number", how="outer")
df.to_excel("1129.xlsx")
相关推荐
开开心心就好5 分钟前
支持多显示器的Windows高效分屏工具
运维·python·科技·游戏·计算机外设·ocr·powerpoint
YXWik61 小时前
图片 OCR 文字提取 (Python + AI 模型(ModelScope))
人工智能·python·ocr
Thecozzy1 小时前
写文档教 AI 用代码
开发语言·python
Hanniel1 小时前
装饰器 (中): 进阶篇,解锁框架级玩法
开发语言·python
康哥爱编程1 小时前
鸿蒙应用开发之应用如何实现腾讯云对象存储?
python·云计算·腾讯云
${王小剑}1 小时前
在pycharm中配置pyside6
ide·python·pycharm
烛之武2 小时前
Python速通笔记
windows·python
挨踢诗人2 小时前
旺店通ERP集成金蝶云星空解决方案
python·数据集成
码界索隆2 小时前
Python转Java系列:作者有话说
java·开发语言·python
未来智慧谷2 小时前
【无标题】
人工智能·python·大模型·ai幻觉