You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python合并两个文件夹中的Excel子集数据?

Python数据处理实现方案

需求回顾

  • 第一个文件夹含4个日期的Excel文件,需仅保留Plot_ID为xxx1格式的行
  • 第二个文件夹的Excel文件包含每个plot的y1-y4标签数据
  • 每个plot对应4个日期的Band数据,需生成带日期后缀的sample_id,并将每个y列与对应plot的所有日期Band数据配对,输出目标格式数据集

实现步骤及代码

1. 导入依赖库

import pandas as pd
import os

2. 读取标签数据(第二个文件夹)

假设第二个文件夹路径为./label_folder,文件名为labels.xlsx:

# 读取标签文件
label_df = pd.read_excel('./label_folder/labels.xlsx')
# 转换plotid为字符串,避免后续拼接sample_id时出现类型错误
label_df['plotid'] = label_df['plotid'].astype(str)

3. 读取并处理所有日期的Band数据(第一个文件夹)

假设第一个文件夹路径为./band_folder,里面的4个Excel文件按日期顺序排列:

band_data_list = []
# 遍历文件夹内的Excel文件,给每个文件加日期标记(1-4)
for idx, filename in enumerate(os.listdir('./band_folder'), start=1):
    if filename.endswith('.xlsx'):
        # 读取单个日期的Band数据
        temp_df = pd.read_excel(os.path.join('./band_folder', filename))
        # 筛选Plot_ID结尾为1的行
        temp_df = temp_df[temp_df['Plot_ID'].astype(str).str.endswith('1')]
        # 转换Plot_ID为字符串,添加日期标记
        temp_df['plotid'] = temp_df['Plot_ID'].astype(str)
        temp_df['date_tag'] = idx
        # 重命名Band列为目标格式X_1.000等
        temp_df.rename(columns={
            'Band_1': 'X_1.000',
            'Band_2': 'X_2.000',
            'Band_3': 'X_3.000',
            'Band_4': 'X_4.000',
            'Band_5': 'X_5.000'
        }, inplace=True)
        # 保留需要的列
        temp_df = temp_df[['plotid', 'date_tag', 'X_1.000', 'X_2.000', 'X_3.000', 'X_4.000', 'X_5.000']]
        band_data_list.append(temp_df)

# 合并所有日期的Band数据
all_band_df = pd.concat(band_data_list, ignore_index=True)

4. 生成每个y列对应的数据集

遍历y1到y4,分别与Band数据合并并输出:

# 逐个处理每个y列
for y_col in ['y1', 'y2', 'y3', 'y4']:
    # 合并Band数据与对应y列的标签
    merged_df = pd.merge(all_band_df, label_df[['plotid', y_col]], on='plotid', how='inner')
    # 生成sample_id:plotid + 日期标记
    merged_df['sample_id'] = merged_df['plotid'] + merged_df['date_tag'].astype(str)
    # 调整列顺序为目标格式
    final_df = merged_df[['sample_id', y_col, 'X_1.000', 'X_2.000', 'X_3.000', 'X_4.000', 'X_5.000']]
    # 重命名y列为统一的'y'
    final_df.rename(columns={y_col: 'y'}, inplace=True)
    # 保存结果为Excel(可选)
    final_df.to_excel(f'{y_col}_dataset.xlsx', index=False)
    # 打印预览结果
    print(f"=== {y_col} 数据集预览 ===")
    print(final_df.head())

关键提示

  • 请根据实际文件路径修改代码中的./label_folder和./band_folder
  • 若第一个文件夹的Excel文件名不按日期顺序排列,可手动指定文件列表保证顺序,示例:
    file_list = ['date_202301.xlsx', 'date_202302.xlsx', 'date_202303.xlsx', 'date_202304.xlsx']
    for idx, filename in enumerate(file_list, start=1):
        # 后续处理逻辑不变
    

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:55:16