Map*_*apa 5 python math numpy scipy
我想知道是否存在一个函数,它会同时计算移动平均值并将其与np.diff
?
如果你有一个数组,你可以计算移动窗口的平均值(移动平均值)并计算该平均值和下一个1元素之间的差值.
例:
a = [1, 3, 4, 5, 15, 14, 16, 13]
b = np.diff(a)
#np.diff makes something like this: `[n] - [n-1]`
#I want something like this: `[n] - np.mean([n-m : n])`
#I would like to have a function, where I could vary `m`:
m = 2
d = [2, 1.5, 10.5, 4, 1.5, -2]
Run Code Online (Sandbox Code Playgroud)
我将如何实现它,以便时间计算不会那么长,因为我想将它用于26000个元素和更高的数组m
?
编辑1:在我给出第一个答案后,OP更新了他的问题。更新后的答案可以在 EDIT2 之后找到。
不确定您到底想做什么,但在这种情况下,您可以简单地执行以下操作以获得diff
:
import numpy as np
diff = np.array(array[n-1:]) - np.array(average[:-n+2])
Run Code Online (Sandbox Code Playgroud)
然后diff
将是所需的输出:
array([ 2. , 1.5, 10.5, 4. , 1.5, -2. ])
Run Code Online (Sandbox Code Playgroud)
因此,您首先使用参数对列表进行切片n
,然后将列表转换为数组并相互减去它们。如果a)你的列表具有相同的长度,b)n
是你的索引而不是你想要开始的元素,c)如果你使用numpy数组而不是列表,上面的代码行会更简单:
import numpy as np
# add one additional value so that the arrays have the same length
myArray = np.array([1, 3, 4, 5, 15, 14, 16, 13, 17])
# choose the starting index rather than the element
n = 2
myAverage = np.array([2, 3.5, 4.5, 10, 14.5, 15, 14.5])
diffAr = myArray[n:] - myAverage
Run Code Online (Sandbox Code Playgroud)
然后diffAr
看起来像这样(因为我向 中添加了一个元素,所以比您的情况多了一个元素myArray
):
array([ 2. , 1.5, 10.5, 4. , 1.5, -2. , 2.5])
Run Code Online (Sandbox Code Playgroud)
只是一般性评论:请不要使用array
anddiff
作为变量名。
编辑2:
你改变了你的问题;现在这是一个更新的答案。在上面的答案中唯一需要添加的是一种计算给定窗口大小的运行平均值的方法m
。之后,人们可以完全按照我上面所做的操作:
import numpy as np
def runningMean(ar, m):
return np.convolve(ar, np.ones((m,))/m)[(m-1):]
a = np.array([1, 3, 4, 5, 15, 14, 16, 13])
m = 2
av = runningMean(a, m)
d = a[m:] - av[:-m]
Run Code Online (Sandbox Code Playgroud)
在这种情况下d
包含所需的输出:
array([ 2. , 1.5, 10.5, 4. , 1.5, -2. ])
Run Code Online (Sandbox Code Playgroud)