python合并excel

本文介绍了如何使用Python的pandas库将多个Excel文件合并到一个文件中,包括按行合并和使用VLOOKUP功能进行基于特定键的合并,以及处理Excel数据的基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

0 思路

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

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

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

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

3. 然后保存到excel

1. 多个文件读取合并

'''
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. 遍历文件夹读取

'''
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功能 

根据某个键合并

'''
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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值