【问题标题】:How to calculate average of sub-lists based on Timestamp values如何根据时间戳值计算子列表的平均值
【发布时间】:2020-06-03 05:39:07
【问题描述】:

我有 2 个列表。第一个列表是测量数据时的时间戳(秒)。第二个列表包含数据。

我想每 10 秒计算一次数据的平均值。请注意,两个连续数据点之间的时间戳不是固定的。

例子:

Timestamp = [2, 5, 8, 11, 18, 23, 25, 28]
Data = [1, 2, 3, 4, 5, 6, 7, 8]

预期的输出应该是:

Output = [average of [1,2,3] , average of [4,5] , average of [6,7,8]]

我想知道 Python 中是否有任何内置函数,例如平均如果分析可以自动完成。

感谢您的帮助。

【问题讨论】:

    标签: python list average sublist


    【解决方案1】:

    您可以使用 floordefaultdict 作为数学函数

    from collections import defaultdict
    from math import floor
    
    timestamp = [2, 5, 8, 11, 18, 23, 25, 28]
    data = [1, 2, 3, 4, 5, 6, 7, 8]
    average_dc= defaultdict(list)
    for t, d in sorted(zip(timestamp, data), key=lambda x : x[0]):
         average_dc[math.floor(t / 10)].append(d)
    averages = [sum(i)/ len(i) for i in average_dc.values()]
    

    输出

    [2.0, 4.5, 7.0]
    

    sorted(zip(timestamp, data), key=lambda x : x[0])timestamp 值与来自data 的值连接到同一索引上,然后for 循环将基于相关timestamp 值插入到average_dc 相关data 值.
    在最后一行,列表推导将遍历average_dc 中的每个列表并计算它的平均值。

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 2014-01-21
      • 2017-03-25
      • 1970-01-01
      • 2020-07-09
      • 2014-11-04
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多