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

使用Python跨Excel多工作表按日期-地点匹配重复项并替换为@

跨多工作表Excel查找日期+地点值重复项并替换的Python实现

核心思路

要解决这个跨表查重替换的问题,关键是先收集所有已出现的「日期-地点列-值」组合,再按工作表原始顺序遍历,对后续表中重复的组合替换为@,同时完整保留每个工作表的原有结构。

实现步骤

  1. 读取目标Excel文件的所有工作表,存储为字典(键为表名,值为对应DataFrame)
  2. 初始化集合,用来记录已经出现过的「日期-地点列-值」三元组
  3. 按原文件的工作表顺序依次处理:
    • 提取每行的日期值
    • 遍历该行所有地点列(排除日期列),检查当前「日期-列名-单元格值」是否已在集合中
    • 若已存在则将单元格替换为@,若不存在则将该三元组加入集合
  4. 将处理后的所有工作表写入新Excel文件,保留原表名和列结构

完整代码

import pandas as pd
from openpyxl import load_workbook

# 替换为你的输入输出文件路径
input_file = "sales_data.xlsx"
output_file = "processed_sales_data.xlsx"

# 读取所有工作表,保留原始顺序
xls = pd.ExcelFile(input_file)
sheet_dict = {name: xls.parse(name) for name in xls.sheet_names}

# 存储已出现的(日期, 地点列, 值)组合
seen_combinations = set()

# 按原工作表顺序处理
for sheet_name in xls.sheet_names:
    df = sheet_dict[sheet_name]
    date_col = df.columns[0]  # 假设第一列为日期列(Date/Place)
    
    for idx, row in df.iterrows():
        current_date = row[date_col]
        # 遍历所有地点列
        for col in df.columns[1:]:
            cell_val = row[col]
            combo = (current_date, col, cell_val)
            if combo in seen_combinations:
                df.at[idx, col] = "@"
            else:
                seen_combinations.add(combo)
    
    sheet_dict[sheet_name] = df

# 写入处理后的文件
with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
    for name, df in sheet_dict.items():
        df.to_excel(writer, sheet_name=name, index=False)

代码说明

  • 若你的Excel中日期列不是第一列,可修改date_col的取值(比如date_col = "Date/Place")
  • 遍历顺序严格遵循原文件的工作表顺序,确保先出现的工作表中的值不会被替换
  • 使用openpyxl引擎支持xlsx格式,同时保留原工作表的名称和列结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:13:22