【问题标题】:Calculate the distance between the sign change in sampled data计算采样数据中符号变化之间的距离
【发布时间】:2017-02-20 17:25:43
【问题描述】:

我想恢复采样数据数组中的周期:

signal = [45, 46, -12, -12.5, 32, 35, 34, 25, 23, -23, -65, -3, 43, 23]

我想计算句号的大小。一个周期从一个正数开始,移动到负数,然后返回一个正数。

例如:

period1=[45 46 -12 -12.5 32]  # length=5
period2=[32 35 34 25 23 -23 -65 -3 43]  # length=8

如何做到这一点?

【问题讨论】:

  • 你误用了“循环”这个词。这意味着非常不同的东西。
  • 你尝试了什么?
  • 描述你观察到的一些想法和问题。这是一项相当简单的任务。
  • 当你问python问题时,我想人们希望看到python。数组中的逗号在哪里?等号前后的空格在哪里?
  • 谢谢,这只是问题的描述

标签: python arrays numpy sampling period


【解决方案1】:

这里的技巧是使用 numpy.diff() 两次。第一个差异可用于查找标志交叉口。第二个差异可用于查找这些交叉点之间的距离。

代码:

import numpy as np

# put the data into a numpy array
signal = np.array(
    [45, 46, -12, -12.5, 0, 32, 35, 34, 25, 23, -23, -65, -3, 43, 23])

# consider zeros to be negative, since we are looking for return to positive
signal[np.where(signal == 0.0)] = -1e-100

# find any returns to positive
return_to_positive = 1 + np.where(2 == np.diff(np.sign(signal)))[0]

# the periods are the distance between `return to positives`
periods = np.diff(return_to_positive)

输出:

>>> print(periods)
[8]

魔法解释:

我们首先需要确保输出数据中没有零。这是因为我们希望 clean 过零。将任何零设置为小于零,因为我们希望第一个正值作为周期的开始。

# consider zeros to be negative, since we are looking for return to positive
signal[np.where(signal == 0.0)] = -1e-100

获取信号的符号,然后对其进行比较。 2 的任何地方都是信号从负到正的地方。将1 添加到索引中,因为之前的diff 从数组中删除了一个元素。 (旁注,pandas 为您执行此操作)

# find the indices for any returns to positive
return_to_positive = 1 + np.where(2 == np.diff(np.sign(signal)))[0]

最后,取每个过零的索引之间的距离以获得周期。

# the periods are the distance between `return to positives`
periods = np.diff(return_to_positive)

【讨论】:

    猜你喜欢
    • 2015-08-13
    • 1970-01-01
    • 2014-11-29
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多