python - 有效地计算非零值的运行

标签 python numpy

我正在处理降雨量的时间序列,为此我想计算单个降雨事件的长度和体积,其中“事件”是一系列非零时间步长。我正在处理 ~60k 时间步长的多个时间序列,我目前的方法很慢。

目前我有以下内容:

import numpy as np

def count_events(timeseries):
    start = 0  
    end = 0
    lengths = []
    volumes = []
    # pad a 0 at the edges so as to include edges as "events"
    for i, val in enumerate(np.pad(timeseries, pad_width = 1, mode = 'constant')):

        if val > 0 and start==0:
            start = i
        if val == 0 and start>0:
            end = i

            if end - start != 1:
                volumes.append(np.sum(timeseries[start:end]))
            elif end - start == 1:
                volumes.append(timeseries[start-1])

            lengths.append(end-start)
            start = 0

    return np.asarray(lengths), np.asarray(volumes)

预期输出:

testrain = np.array([1,0,1,0,2,2,8,2,0,0,0.1,0,0,1])
lengths, volumes = count_events(testrain)
print lengths
[1 1 4 1 1]
print volumes
[  1.    1.   12.    0.1   1. ] # 12 should actually be 14, my code returns wrong results.

我想有更好的方法来做到这一点,利用 numpy 的效率,但没有想到......

编辑:

比较不同的解决方案:

testrain = np.random.normal(10,5, 60000)
testrain[testrain<0] = 0 

我的解决方案(产生错误的结果,不确定原因):

%timeit count_events(testrain)
#10 loops, best of 3: 129 ms per loop

@dawg 的:

%timeit dawg(testrain) # using itertools
#10 loops, best of 3: 113 ms per loop
%timeit dawg2(testrain) # using pure numpy
#10 loops, best of 3: 156 ms per loop

@DSM 的:

%timeit DSM(testrain)
#10 loops, best of 3: 28.4 ms per loop

@DanielLenz 的:

%timeit DanielLenz(testrain)
#10 loops, best of 3: 316 ms per loop

最佳答案

虽然您可以在纯 numpy 中执行此操作,但您基本上是将 numpy 应用于 pandas问题。您的 volume 是 groupby 操作的结果,您可以在 numpy 中伪造它,但它是 pandas 原生的。

例如:

>>> tr = pd.Series(testrain)
>>> nonzero = (tr != 0)
>>> group_ids = (nonzero & (nonzero != nonzero.shift())).cumsum()
>>> events = tr[nonzero].groupby(group_ids).agg([sum, len])
>>> events
    sum  len
1   1.0    1
2   1.0    1
3  14.0    4
4   0.1    1
5   1.0    1

关于python - 有效地计算非零值的运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32698196/

相关文章:

python - 递归:带有 `scipy.lfilter` 的 IIR 滤波器

python - 有效地计算 numpy 数组中的排序排列

python - 如何使用时间而不使用按钮命令更改 tkinter 中的帧

python - 无法在 python 3.5(pip、ubuntu 3.5)上安装 'secrets'

python - 在 flask 中返回 HTTP 状态码 201

python - Numpy 屏蔽操作

python - Django/Python,在每个用户请求上调用特定的类/函数

python - 根据列的最小值选择两列值

python - 不能根据数据在现有图上绘制计算的质心值

python - 如何处理 Python 中的不确定形式