Python:如何找到不同符号值之间的时间间隔?

时间:2016-03-18 21:32:39

标签: python arrays loops

你好我想计算信号一阶导数的两个零的时间差。例如,假设一阶导数是:

d =[-0.2, 0.3, 0.2, 0.2, -0.1, 0.5]
t =[   0,  13,  22,  23,   34,  50]

我想要一个数组c

c = [(13-0), (34-13), (50-34)], i.e. c = [12, 21, 16]

假设我在user中为不同的pUser记录了原始数据。

z = list()
for i in user:
    sort_ind = np.argsort(pUser.time[i])
    time_vec = pUser.time[i][sort_ind]
    val_vec = pUser.val[i][sort_ind]
    tmp0 = np.diff(val_vec)   
    s = np.sign(tmp0[0])  ## Sign of the first value (+1 or -1)
    index = 0
    zz = list()
    for j in range(1,len(tmp0)):
        if (np.sign(tmp0[j]) + s)==0:
            s = np.sign(tmp0[j])
            dt = (time_vec[j]-time_vec[index])/(2*np.timedelta64(1, 's'))
            zz.append(dt)
            index = j
    z.append(zz)

但是由于len(tmp0) ~ 10^4-10^5循环需要一段时间。我想知道是否有更快的方法来避免这种循环。

1 个答案:

答案 0 :(得分:0)

一个纯粹的numpy答案怎么样:

=ArrayFormula(IF(C2:C="",IFERROR(1/0),IF(C2:C="Immediate",D2:D+1,IF(C2:C="3 Day",WORKDAY(D2:D,3,Holidays!$B$2:$B$11),IF(C2:C="5 Day",WORKDAY(D2:D,5,Holidays!$B$2:$B$11),IF(ISBLANK(C2:C),IFERROR(1/0)))))))

输出

import numpy as np

a = np.array([[-0.2, 0.3, 0.2, 0.2, -0.1, 0.5],
              [   0,  13,  22,  23,   34,  50]])

# mask of all the positive values
sign = a[0] > 0

# mask of any location where the sign changed
mask = np.insert(sign[:-1] ^ sign[1:], 0, True)

# mask all the sign changes and diff
c = np.diff(a[1,mask])