将带TimeStamp的数值数据转换为值持续时长统计格式
时间序列数据合并为连续值区间
需求说明
将按时间递增排列的时间戳-数值序列,合并为展示每个数值持续区间的格式:起始时间(包含)、结束时间(不包含)、对应数值。最后一个区间的结束时间标记为null。
输入数据
| TimeStamp | Value |
|---|---|
| ts1 | 10 |
| ts2 | 20 |
| ts3 | 20 |
| ts4 | 30 |
| ts5 | 40 |
| ts6 | 40 |
| ts7 | 10 |
输出结果
| startTime(Inclusive) | endtime (Exclusive) | Value |
|---|---|---|
| ts1 | ts2 | 10 |
| ts2 | ts4 | 20 |
| ts4 | ts5 | 30 |
| ts5 | ts7 | 40 |
| ts7 | null | 10 |
实现思路(以Python为例)
遍历输入序列,记录当前数值的起始时间;当遇到数值变化时,将当前区间写入结果集,同时更新起始时间和当前数值。遍历结束后,单独处理最后一个未闭合的区间。
def merge_continuous_values(data): if not data: return [] result = [] current_val = data[0]['Value'] start_ts = data[0]['TimeStamp'] for idx in range(1, len(data)): curr_ts, curr_val = data[idx]['TimeStamp'], data[idx]['Value'] if curr_val != current_val: result.append({ 'startTime(Inclusive)': start_ts, 'endtime (Exclusive)': curr_ts, 'Value': current_val }) current_val = curr_val start_ts = curr_ts # 处理最后一个区间 result.append({ 'startTime(Inclusive)': start_ts, 'endtime (Exclusive)': 'null', 'Value': current_val }) return result # 输入数据示例 input_data = [ {'TimeStamp': 'ts1', 'Value': 10}, {'TimeStamp': 'ts2', 'Value': 20}, {'TimeStamp': 'ts3', 'Value': 20}, {'TimeStamp': 'ts4', 'Value': 30}, {'TimeStamp': 'ts5', 'Value': 40}, {'TimeStamp': 'ts6', 'Value': 40}, {'TimeStamp': 'ts7', 'Value': 10} ] # 生成并打印结果 output = merge_continuous_values(input_data) for item in output: print(item)
内容的提问来源于stack exchange,提问作者Gitesh Khanna
相关产品推荐
相关产品推荐

