import pandas as pd # 示例数据 data = { 'state': [0, 21201000300, 21201000300, 0, 21201000001, 21201000001, 21201000002, 21201000002, 0], 'simTime': [0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08] } # 创建DataFrame df = pd.DataFrame(data) # 目标错误码列表 target_error_codes = [21201000300, 21201000001, 21201000002] # 初始化一个字典来存储每个错误码的时间段 error_periods = {error_code: [] for error_code in target_error_codes} # 遍历DataFrame,检测目标错误码并统计时间段 current_error_code = None start_time = None for index, row in df.iterrows(): if row['state'] in target_error_codes: if current_error_code is None or current_error_code != row['state']: # 如果当前错误码与前一个不同,或者这是第一个错误码,则记录新的时间段开始 current_error_code = row['state'] start_time = row['simTime'] else: # 如果当前行不是目标错误码,并且我们之前记录了一个错误码,则记录时间段结束 if current_error_code is not None: # 注意:这里我们假设下一个非匹配行的时间不是当前错误码的时间段的一部分 # 但为了包含整个错误码持续的时间,我们不减去任何时间 error_periods[current_error_code].append((start_time, row['simTime'])) current_error_code = None # 处理最后一个错误码的时间段(如果DataFrame以错误码结束) if current_error_code is not None: # 由于我们想要包含最后一个错误码的时间点,所以我们需要检查是否有下一个时间点 # 如果没有(即这是DataFrame的最后一行),我们就直接使用最后一个时间点 end_time = df['simTime'].iloc[-1] if current_error_code == df['state'].iloc[-1] else df['simTime'].iloc[-2] error_periods[current_error_code].append((start_time, end_time)) # 格式化时间段并输出结果 for error_code, periods in error_periods.items(): print("error_periods is", error_periods) if periods: print(f"Error Code {error_code} has the following time periods:") for start, end in periods: print(f" {start:.2f} to {end:.2f}") else: print(f"No time periods found for Error Code {error_code}.")