【问题标题】:Extracting continuous values above a certain threshold in a Numpy array在 Numpy 数组中提取高于某个阈值的连续值
【发布时间】:2021-02-26 14:19:43
【问题描述】:

对于一个学校项目,我需要实现以下功能:

创建一个函数find_intervals(s, threshold),在输入中接收一个Series s和一个阈值。

找到信号高于给定阈值的连续周期。

该函数应返回一个系列,该系列以每个连续周期的开始日期为索引,并以天数表示的周期长度作为关联值。结果应按周期长度降序排列。

当应用于这样的信号时(橙色线,thershold=0):

它应该返回以下系列:

70     35
140    35
1      34
Name: interval, dtype: int64

也就是说,最大间隔是 35 个单位,它从标签 70 开始,然后还有一个长度为 35 的间隔从 140 开始,依此类推。在练习中,索引将是日期和间隔的长度以天为单位。

我已经编写了以下函数(在this Stackoverflow answer的帮助下。)

def intervals(samples,threshold):
    samples = np.array(samples)
    start = -1
    intervals = []
    for idx,x in enumerate(samples):
        if start < 0 and abs(x) < threshold:
            start = idx
        elif start >= 0 and abs(x) >= threshold:
            dur = idx-start
            if dur >= 0:
                intervals.append((start))
            start = -1
    return intervals

但是,当我在类似的 Sin 波上调用此函数时,该函数不适用于阈值 0 或任何负值。我真的不知道为什么。

编辑:这是我尝试过的以及得到的结果;

在下面的文章中,我绘制了一个简单的 Sin 波。

x = np.arange(0,64*np.pi,1) 
y = np.sin(x/11)
df = pd.Series(data=y,index=x)
plt.plot(x,y)
df = np.array(df)

当我使用intervals(df,0.5) 运行代码时,我得到了 [0, 34, 69, 103, 138, 172] 这是预期的。

但是;

如果我这样做了; intervals(df,0)我得到一个空列表,对于任何负阈值都可以这样说。

【问题讨论】:

  • abs(x) &gt;= threshold 在这里,您取的是 x 的绝对值。如果使用阈值 0,则比较 abs(x) &gt;= threshold 将始终为真。

标签: python pandas numpy signals signal-processing


【解决方案1】:

将您的功能更改为:

def find_intervals2(samples, threshold):
    samp = samples[samples >= threshold]
    xx = samp.groupby((samp.index != samp.index.to_series().shift() + 1)
        .cumsum()).apply(lambda grp: (grp.index[0], grp.size))
    return pd.Series(xx.str[1].values, index=xx.str[0]).sort_values(ascending=False)

请注意,结果是系列而不是列表

为了提供一个更有启发性的示例,将源系列定义为:

x = np.arange(0, 68 * np.pi, dtype=int)
y2 = np.sin(x / 11 * (1000 - x) // 7 / 142)
s2 = pd.Series(data=y2, index=x)
plt.plot(s2)
plt.grid(True);

注意绘图的“逐步减少”频率。

那么当你运行find_intervals(s2, -0.2) 时,结果是:

162    52
72     48
0      39
dtype: int64

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 2021-09-01
    相关资源
    最近更新 更多