python - 优化迭代检查连续值之间的最大差异

标签 python python-2.7 numpy

我有一个 int_16 的二进制文件。它们被排序到 nx2 数组中,其中每列包含正弦曲线的样本。

我正在检查每个连续值,看看两个值之间的幅度差异是否大于某个值。这是执行该任务的一些代码。有什么更好的方法来做到这一点?我正在使用Python 2.7

import numpy as np

DIFF_MAX = 100
errcnt = 0

f = open("samp.bin","rb")
a = np.fromfile(f, dtype=np.int16)
n = np.reshape(a, (-1,2))

for i in range(0,len(a)/2 - 2):
    if(abs(abs(n[i,0])-abs(n[i+1,0])) > DIFF_MAX):
            errcnt = errcnt + 1
            print "ERROR!!!"
    if(abs(abs(n[i,1])-abs(n[i+1,1])) > DIFF_MAX):
            errcnt = errcnt + 1
            print "ERROR!!!"

print str(errcnt) + " errors found out of " + str(len(a)/2)

我认为这样做本质上会很慢,我只是好奇是否有更好的方法。谢谢。

运行时,

time python test.py 
0 errors found out of 4329472

real    0m21.025s
user    0m20.950s
sys 0m0.075s

最佳答案

您可以通过将数组相对于彼此移动一个位置并减去它们来完成此操作。

abs(abs(n[1::,:]) - abs(n[:-1,:])) > DIFF_MAX

只要第一维上两个连续值之间的差异大于 DIFF_MAXFALSE,生成的 bool 数组就会用 TRUE 指示位置> 其他地方。

关于python - 优化迭代检查连续值之间的最大差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54583560/

相关文章:

c# - 使用 Auth0 授权来 self 们的 SPA 和其他后端服务的 API 请求

python为类的每次调用获取新的随机名称

python - Pandas - 如何从数据框中获取索引值

.net - 在 Python 中动态编写 PowerShell CmdLets

python-2.7 - python opencv2 中的 libpng 警告

python-2.7 - 是否有可能同时具有一对多和多对多关系的模型?

python - 矩阵与标量数组的 Numpy 乘法,没有 for 循环

numpy - 使用 scipy 的低通冷杉滤波器参数

python - numpy:对多维数组进行操作

python - Python中的多对多数据结构