简体   繁体   中英

How to ignore specific numbers in a numpy moving average?

Let's say I have a simple numpy array:

a = np.array([1,2,3,4,5,6,7])

I can calculate the moving average of a window with size 3 simply like:

np.convolve(a,np.ones(3),'valid') / 3

which would yield

array([2., 3., 4., 5., 6.])

Now, I would like to take a moving average but exclude anytime the number '2' appears. In other words, for the first 3 numbers, originally, it would be (1 + 2 + 3) / 3 = 2. Now, I would like to do (1 + 3) / 2 = 2. How can I specify a user-defined number to ignore and calculate the running mean without including this user-defined number? I would like to keep this to some sort of numpy function without bringing in pandas.

You could replace the unwanted values with 0 using a mask and separately compute the number of valid items, then compute the ratio:

a = np.array([1,2,3,4,5,6,7])

mask = a != 2

num = np.convolve(np.where(mask, a, 0), np.ones(3), 'valid')
denom = np.convolve(mask, np.ones(3), 'valid')

out = num/denom

Output:

array([2. , 3.5, 4. , 5. , 6. ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM