如何验证每日重置的交易编号连续性?ChatGPT代码失效求助
交易编号连续性验证问题及修复方案
需求:数据库包含TransactionDate和TransactionNumber字段,需用Python验证每日的交易编号是否从1开始连续,将不连续的具体记录导出到Excel。原ChatGPT生成的代码会返回整日期的所有记录,无法精准定位异常行。
示例数据
| TransactionDate | TransactionNumber | 备注 |
|---|---|---|
| 08/11/2023 | 1 | 正常 |
| 08/11/2023 | 2 | 正常 |
| 08/11/2023 | 3 | 正常 |
| 08/12/2023 | 1 | 正常 |
| 08/12/2023 | 2 | 正常 |
| 08/12/2023 | 3 | 正常 |
| 08/13/2023 | 1 | 正常 |
| 08/13/2023 | 3 | 需要捕获的异常(跳号) |
| 08/13/2023 | 3 | 需要捕获的异常(重复) |
原错误代码
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'.")
错误分析
- 日期转换错误:代码错误地将
TransactionNumber(交易编号)转换为日期类型,而非TransactionDate字段,导致后续分组逻辑完全失效。 - 异常定位错误:原代码仅标记存在异常的日期,然后导出该日期的所有记录,无法精准定位到跳号、重复的具体异常行。
修复后的正确代码
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'")
代码说明
- 日期转换:正确将
TransactionDate转换为datetime类型,确保分组逻辑准确。 - 分组排序:每组内先按交易编号排序,避免因原始数据顺序混乱导致的误判。
- 异常标记:
- 对比实际编号与从1开始的连续预期序列,标记跳号记录;
- 标记所有重复的交易编号;
- 精准导出:仅筛选标记为异常的具体行导出,而非整日期的所有记录。
内容的提问来源于stack exchange,提问作者Tegman
相关产品推荐
相关产品推荐

