匹配一个文件夹下的所有excel——python

匹配一个文件夹下的所有excel------python(这里写自定义目录标题)

下面展示使用OID匹配所有excel文件的 代码片。这里的OID对应你匹配的基准变量。

首先,保证所有文件中都存在OID,且对应的目标样本相同。

然后,将路径(文件保存地址)和OID换成自己的就可以了

javascript 复制代码
#导入相关库
import os
import pandas as pd

# 设置文件夹路径,这里""中改成你自己的路径
excel_folder = r"C:\Users\lenovo\Desktop\map"

# 获取文件夹中所有 Excel 文件
excel_files = [f for f in os.listdir(excel_folder) if f.endswith('.xls') or f.endswith('.xlsx')]

# 初始化一个空的 DataFrame 用于合并所有结果
merged_df = pd.DataFrame()

# 遍历每个 Excel 文件
for excel_file in excel_files:
    try:
        # 构建文件路径
        excel_path = os.path.join(excel_folder, excel_file)

        # 读取 Excel 文件
        df = pd.read_excel(excel_path)

        # 检查是否包含 'OID' 列
        if 'OID' in df.columns:
            # 如果是第一个文件,则初始化 merged_df
            if merged_df.empty:
                merged_df = df
            else:
                # 基于 'OID' 列进行合并
                merged_df = pd.merge(merged_df, df, on='OID', how='outer')

            print(f"Successfully processed {excel_file}.")
        else:
            print(f"Warning: 'OID' column not found in {excel_file}. Skipping file.")

    except Exception as e:
        print(f"Error processing {excel_file}: {e}")

# 导出合并后的结果到新的 Excel 文件
output_path = os.path.join(excel_folder, "merged_output.xlsx")
merged_df.to_excel(output_path, index=False)

print(f"All processing complete. Results saved to {output_path}")
相关推荐
少控科技几秒前
QT高阶日记010
开发语言·qt
西红市杰出青年2 分钟前
asyncio.gather 内部原理与运行机制(详解)
网络·python·异步
秦jh_2 分钟前
【Qt】界面优化
开发语言·qt
70asunflower3 分钟前
torch.manual_seed()介绍
人工智能·pytorch·python
阿蒙Amon6 分钟前
C#每日面试题-简述泛型约束
java·开发语言·c#
zh_xuan7 分钟前
kotlin 延迟属性
开发语言·kotlin
西红市杰出青年11 分钟前
Playwright 的 BrowserContext 与 Page:原理与实践指南
python
Tianwen_Burning15 分钟前
pycharm下配置halcon
python
进击的小头16 分钟前
创建型模式:简单工厂模式(C语言实现)
c语言·开发语言·简单工厂模式
汉堡go17 分钟前
python_chapter6
前端·数据库·python