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

如何验证每日重置的交易编号连续性?ChatGPT代码失效求助

交易编号连续性验证问题及修复方案

需求:数据库包含TransactionDate和TransactionNumber字段,需用Python验证每日的交易编号是否从1开始连续,将不连续的具体记录导出到Excel。原ChatGPT生成的代码会返回整日期的所有记录,无法精准定位异常行。

示例数据

TransactionDateTransactionNumber备注
08/11/20231正常
08/11/20232正常
08/11/20233正常
08/12/20231正常
08/12/20232正常
08/12/20233正常
08/13/20231正常
08/13/20233需要捕获的异常(跳号)
08/13/20233需要捕获的异常(重复)

原错误代码

import pandas as pd

# Load data from Excel file into a pandas DataFrame
df = pd.read_excel("BDPO_database.xlsx", sheet_name='Sheet1')

# Convert date to datetime
df['TransactionDate'] = pd.to_datetime(df['TransactionNumber'])  # 错误:把交易编号转成了日期

# Create a function to check for non-sequential event numbers
def check_non_sequential(series):
    return ~series.diff().eq(1).all()

# Group by date and apply the function to check for non-sequential event numbers within each group
non_sequential_records = df.groupby('TransactionDate')['TransactionNumber'].apply(check_non_sequential)

# Get the dates with non-sequential event numbers
non_sequential_dates = non_sequential_records[non_sequential_records].index

# Filter out non-sequential records and export to an Excel file
non_sequential_df = df[df['TransactionDate'].isin(non_sequential_dates)]  # 错误:返回整日期所有记录,而非具体异常行
non_sequential_df.to_excel('non_sequential_records.xlsx', index=False)
print("Registros não sequenciais exportados para 'non_sequential_records.xlsx'.")

错误分析

  1. 日期转换错误:代码错误地将TransactionNumber(交易编号)转换为日期类型,而非TransactionDate字段,导致后续分组逻辑完全失效。
  2. 异常定位错误:原代码仅标记存在异常的日期,然后导出该日期的所有记录,无法精准定位到跳号、重复的具体异常行。

修复后的正确代码

import pandas as pd

# 读取Excel数据
df = pd.read_excel("BDPO_database.xlsx", sheet_name='Sheet1')

# 正确转换日期字段(注意根据实际日期格式调整format参数)
df['TransactionDate'] = pd.to_datetime(df['TransactionDate'], format="%m/%d/%Y")

# 按日期分组,对每组的交易编号排序后检查连续性
def mark_abnormal_records(group):
    # 先按交易编号排序,确保顺序正确
    sorted_group = group.sort_values('TransactionNumber').reset_index(drop=True)
    # 生成预期的连续编号序列(从1开始)
    expected_numbers = pd.Series(range(1, len(sorted_group)+1))
    # 标记异常行:实际编号与预期不符,或存在重复
    sorted_group['is_abnormal'] = (sorted_group['TransactionNumber'] != expected_numbers) | sorted_group['TransactionNumber'].duplicated(keep=False)
    return sorted_group

# 应用分组处理,获取标记后的全量数据
marked_df = df.groupby('TransactionDate', group_keys=False).apply(mark_abnormal_records)

# 筛选出异常记录并导出
abnormal_df = marked_df[marked_df['is_abnormal']].drop(columns='is_abnormal')
abnormal_df.to_excel('non_sequential_records.xlsx', index=False)

print("异常交易记录已导出至 'non_sequential_records.xlsx'")

代码说明

  1. 日期转换:正确将TransactionDate转换为datetime类型,确保分组逻辑准确。
  2. 分组排序:每组内先按交易编号排序,避免因原始数据顺序混乱导致的误判。
  3. 异常标记:
    • 对比实际编号与从1开始的连续预期序列,标记跳号记录;
    • 标记所有重复的交易编号;
  4. 精准导出:仅筛选标记为异常的具体行导出,而非整日期的所有记录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 00:20:20