【问题标题】:Running average / frequency of time series data?时间序列数据的运行平均值/频率?
【发布时间】:2012-11-14 21:01:10
【问题描述】:

给定一个数据集,例如:

[2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 65, 75, 85, 86, 87, 88]

这些值总是在增加(实际上是时间),我想找出这些值之间的运行平均距离。我实际上是在尝试确定数据何时从“每秒 1”变为“每 5 秒 1”(或任何其他值)。

我在 Python 中实现这个,但任何语言的解决方案都是最受欢迎的。

我正在寻找上面的示例输入的输出将类似于:

[(2, 1), (10, 5), (55, 10), (85, 1) ]

其中,“2”表示值之间的距离从“1”开始的位置,并且, “10”表示距离变为“5”的位置。 (它必须准确地在那里,如果稍后检测到移位,那也没关系。)

我正在寻找值之间的平均距离何时发生变化。我意识到在算法的稳定性和对输入变化的敏感性之间会有某种权衡。

(顺便说一句,PandasNumPy 有用吗?)

【问题讨论】:

  • 你如何从中得到[(2, 1), (10, 5)]
  • @BrenBarn,更新问题
  • 我仍然不确定你的意思——你能发布一些伪代码,或者一个更简单的例子吗?
  • @SteveMayne,我使用了错误的示例输入数据。我也需要一些“模糊”输出的措施,因为我实际上只对某些离散距离感兴趣。 (1 秒、5 秒、15、30 和 60 等等)但我认为这会过多地偏离问题的核心,所以我决定将其省略。不幸的是,我直到现在才清理示例输入数据。 (已编辑。)现在问题更清楚了吗?
  • 如果我没听错的话,我认为最后一个元组应该是(85, 1)

标签: python algorithm numpy pandas average


【解决方案1】:

您可以像这样使用 numpy 或 pandas(“pandas 版本”):

In [256]: s = pd.Series([2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 35,
                             40, 45, 50, 55, 65, 75, 85, 86, 87, 88])

In [257]: df = pd.DataFrame({'time': s,
                             'time_diff': s.diff().shift(-1)}).set_index('time')

In [258]: df[df.time_diff - df.time_diff.shift(1) != 0].dropna()
Out[258]: 
      time_diff
time           
2             1
10            5
55           10
85            1

如果您只想查看每个时间步的第一次出现,您也可以使用:

In [259]: df.drop_duplicates().dropna() # set take_last=True if you want the last
Out[259]: 
      time_diff
time           
2             1
10            5
55           10

但是对于 pandas,您通常会使用 DatetimeIndex 来使用内置的时间序列功能:

In [44]: a = [2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 35,
              40, 45, 50, 55, 65, 75, 85, 86, 87, 88]

In [45]: start_time = datetime.datetime.now()

In [46]: times = [start_time + datetime.timedelta(seconds=int(x)) for x in a]

In [47]: idx = pd.DatetimeIndex(times)

In [48]: df = pd.DataFrame({'data1': np.random.rand(idx.size), 
                            'data2': np.random.rand(idx.size)},
                           index=idx)

In [49]: df.resample('5S') # resample to 5 Seconds
Out[49]: 
                        data1     data2
2012-11-28 07:36:35  0.417282  0.477837
2012-11-28 07:36:40  0.536367  0.451494
2012-11-28 07:36:45  0.902018  0.457873
2012-11-28 07:36:50  0.452151  0.625526
2012-11-28 07:36:55  0.816028  0.170319
2012-11-28 07:37:00  0.169264  0.723092
2012-11-28 07:37:05  0.809279  0.794459
2012-11-28 07:37:10  0.652836  0.615056
2012-11-28 07:37:15  0.508318  0.147178
2012-11-28 07:37:20  0.261157  0.509014
2012-11-28 07:37:25  0.609685  0.324375
2012-11-28 07:37:30       NaN       NaN
2012-11-28 07:37:35  0.736370  0.551477
2012-11-28 07:37:40       NaN       NaN
2012-11-28 07:37:45  0.839960  0.118619
2012-11-28 07:37:50       NaN       NaN
2012-11-28 07:37:55  0.697292  0.394946
2012-11-28 07:38:00  0.351824  0.420454

在我看来,对于使用时间序列来说,Pandas 是迄今为止 Python 生态系统中最好的库。不确定你真正想做什么,但我会试试 pandas。

【讨论】:

  • 这是来自 REPL(例如 iPython)的日志吗?
  • 是的,它是 ipython。非常喜欢交互式编程和检查对象
  • 只是说,这在numpy中也基本可以做到。
  • @seberg 你是对的。我会更新答案以反映这一点。
  • @seberg 我添加了一些从头开始用 numpy 很难实现的代码 ;-)。
【解决方案2】:

我很喜欢通过islice 使用窗口函数,它非常有用,我发现自己经常重复使用它:

from itertools import islice

def window(seq, n=2):
    """
    Returns a sliding window (of width n) over data from the iterable
    s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   
    """
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

# Main code:
last_diff = None
results = []
for v1, v2 in window(a):
    diff = abs(v1 - v2)
    if diff != last_diff:
        results.append((v1, diff))
    last_diff = diff

结果:

[(2, 1), (10, 5), (30, 4), (34, 6), (40, 5), (45, 1), (46, 4), (50, 5)]

【讨论】:

  • 滑动窗口可能是我正在寻找的,因为我需要稍微“模糊”输出,因为输入不准确并且可能会有些抖动。
【解决方案3】:

在 Python 中:

a = [2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 34, 40, 45, 46, 50, 55]
# zip() creates tuples of two consecutive values 
# (it zips lists of different length by truncating longer list(s))
# then tuples with first value and difference are placed in 'diff' list
diff = [(x, y-x) for x, y in zip(a, a[1:])]
# now pick only elements with changed difference 
result = []
for pair in diff:
    if not len(result) or result[-1][1]!=pair[1]: # -1 to take last element
        result.append(pair)

【讨论】:

    【解决方案4】:

    这个生成器怎么样:

    L = [2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 34, 40, 45, 46, 50, 55]
    
    def differences_gen(L, differences):
        previous = L[0]
        differences = iter(differences + [None])
        next_diff = next(differences)
        for i, n in enumerate(L[1:]):
            current_diff = n - previous
            while next_diff is not None and current_diff >= next_diff:
                yield (previous, next_diff)
                next_diff = next(differences)
            previous = n
    
    list(differences_gen(L, [1,5]))
    # [(2, 1), (10, 5)]
    

    可能有一种更简洁的方法来迭代分区,但使用生成器应该可以让它在Ldifferences 更长时间内保持高效。

    【讨论】:

    • 非常聪明。你回答了我偶然问到的问题。 :-) +1(我看到你用差异参数过滤掉差异?)
    【解决方案5】:
    a = [2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 34, 40, 45, 46, 50, 55]
    
    ans = [(a[0], a[1]-a[0])]
    for i in range(1, len(a)-1):
        if a[i+1] - a[i] - a[i] + a[i-1] is not 0:
            ans.append((a[i], a[i+1]-a[i]))
    
    print ans
    

    输出:

    [(2, 1), (10, 5), (30, 4), (34, 6), (40, 5), (45, 1), (46, 4), (50, 5)]
    

    这是你想要的吗?

    【讨论】:

      猜你喜欢
      • 2014-02-10
      • 2014-02-24
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      • 1970-01-01
      • 2016-04-05
      相关资源
      最近更新 更多