【问题标题】:Python: how to find the time interval between values of different sign?Python:如何找到不同符号值之间的时间间隔?
【发布时间】:2016-07-05 19:28:08
【问题描述】:

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

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]

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

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,该循环需要一段时间。我想知道是否有更快的方法避免该循环。

【问题讨论】:

  • 10^9?这会很难..
  • 其实少了,抱歉我改了尺寸
  • 请问您需要多长时间?
  • 您能否提供cdt 与循环中使用的变量的关系?

标签: python arrays loops


【解决方案1】:

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

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])

输出

In [2]: c
Out[2]: array([ 13.,  21.,  16.])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多