Function similar to numpy diff function

I was wondering if there is a function that will calculate the moving average at the same time and combine it with np.diff ?

If you have an array, and you would calculate the average for the moving window (moving average) and calculate the difference between this average and the next 1 element.

Example:

 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([nm : 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] 

How would I implement it, so the calculation of the time would not be so big, since I would like to use it for an array of 26,000 elements and above m ?

+5
source share
1 answer

Edit 1: OP updated his question after I gave my first answer. An updated answer can be found below after EDIT2.

Not sure what exactly you are trying to do, but in this case you could just do the following to get diff :

 import numpy as np diff = np.array(array[n-1:]) - np.array(average[:-n+2]) 

Then diff will be the desired output:

 array([ 2. , 1.5, 10.5, 4. , 1.5, -2. ]) 

So, you first chop your lists with the n parameter, and then convert your lists into arrays and subtract them from each other. The above line of code will be even simpler if: a) your lists were the same length; b) n was your index, not the element you want to start with, and c) if you used numpy arrays instead of lists:

 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 

Then diffAr looks like this (one element is larger than in your case, since I added one element to myArray ):

 array([ 2. , 1.5, 10.5, 4. , 1.5, -2. , 2.5]) 

Just a general comment: Please do not use array and diff as variable names.

EDIT2:

You have changed your question; now the updated answer. The only thing that needs to be added to the answer above is the way to calculate the average value for a given window size m . After that, you can do what I did above:

 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] 

In this case, d contains the desired result:

 array([ 2. , 1.5, 10.5, 4. , 1.5, -2. ]) 
+3
source

Source: https://habr.com/ru/post/1240912/


All Articles