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

Python中如何合并不同时间间隔的两组(time:speed)数据并绘制求和图?

合并不同时间间隔的端口速度数据并求和

要解决两个端口离散时间速度数据的合并求和问题,核心是捕捉所有速度变化的时间点,并计算每个时间点对应的两个端口最新速度之和(因为端口速度在相邻记录时间点之间保持不变)。以下是具体实现方案:

实现思路

  1. 对两个端口的时间-速度数据按时间排序,拆分出独立的时间列表和速度列表。
  2. 收集两个端口所有的时间点,去重后排序,得到所有需要计算总和的关键时间点。
  3. 对每个关键时间点,用二分查找快速定位两个端口在该时间点之前的最新速度,求和后存入合并结果。

完整代码示例

import datetime
from bisect import bisect_right
import matplotlib.pyplot as plt

# 示例数据(替换为你的实际数据)
port_1_info = {
    datetime.datetime(2022, 12, 4, 4, 27, 24): 158,
    datetime.datetime(2022, 12, 4, 4, 27, 25): 44,
    datetime.datetime(2022, 12, 4, 4, 27, 32): 90,
    datetime.datetime(2022, 12, 4, 4, 27, 37): 158,
    datetime.datetime(2022, 12, 4, 4, 27, 41): 181,
}

port_2_info = {
    datetime.datetime(2022, 12, 4, 4, 27, 23): 50,
    datetime.datetime(2022, 12, 4, 4, 27, 26): 80,
    datetime.datetime(2022, 12, 4, 4, 27, 35): 120,
    datetime.datetime(2022, 12, 4, 4, 27, 40): 60,
}

# 处理端口1数据:排序并拆分时间、速度列表
sorted_p1 = sorted(port_1_info.items())
times_p1, speeds_p1 = zip(*sorted_p1) if sorted_p1 else ([], [])

# 处理端口2数据:排序并拆分时间、速度列表
sorted_p2 = sorted(port_2_info.items())
times_p2, speeds_p2 = zip(*sorted_p2) if sorted_p2 else ([], [])

# 获取所有唯一时间点并排序
all_times = sorted(set(times_p1) | set(times_p2))

merged_total = {}
for current_time in all_times:
    # 查找端口1在当前时间的最新速度
    idx_p1 = bisect_right(times_p1, current_time) - 1
    speed_p1 = speeds_p1[idx_p1] if idx_p1 >= 0 else 0  # 无数据时默认速度为0,可调整
    
    # 查找端口2在当前时间的最新速度
    idx_p2 = bisect_right(times_p2, current_time) - 1
    speed_p2 = speeds_p2[idx_p2] if idx_p2 >= 0 else 0
    
    merged_total[current_time] = speed_p1 + speed_p2

# 转换为排序后的列表用于matplotlib绘图
sorted_merged = sorted(merged_total.items())
plot_times, plot_speeds = zip(*sorted_merged)

# 绘图展示
plt.figure(figsize=(12, 6))
plt.plot(plot_times, plot_speeds, marker='o', linestyle='-', label='Total Speed')
plt.xlabel('Time')
plt.ylabel('Total Speed')
plt.title('Daily Total Speed (Port 1 + Port 2)')
plt.xticks(rotation=45)
plt.legend()
plt.tight_layout()
plt.show()

关键细节说明

  • 二分查找效率:使用bisect_right替代遍历,在数据量较大时能显著提升速度,快速找到每个时间点对应的最新速度记录。
  • 初始速度处理:代码中默认端口无历史数据时速度为0,若你的设备有初始速度(比如开机默认值),直接替换0为对应数值即可。
  • 完整时间覆盖:合并所有端口的时间点,确保每一次速度变化都被捕捉,绘图结果能准确反映全天速度总和的波动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 06:40:35