Let's say I have an array of 100 random numbers called random_array. I need to create an array that averages x numbers in random_array and stores them.
So if I had x = 7, then my code finds the average of the first 7 numbers and stores them in my new array, then next 7, then next 7...
I currently have this but I'm wondering how I can vectorize it or use some python method:
random_array = np.random.randint(100, size=(100, 1))
count = 0
total = 0
new_array = []
for item in random_array:
if (count == 7):
new_array.append(total/7)
count = 0
total = 0
else:
count = count + 1
total = total + item
print new_array
Here's the standard trick
def down_sample(x, f=7):
# pad to a multiple of f, so we can reshape
# use nan for padding, so we needn't worry about denominator in
# last chunk
xp = np.r_[x, nan + np.zeros((-len(x) % f,))]
# reshape, so each chunk gets its own row, and then take mean
return np.nanmean(xp.reshape(-1, f), axis=-1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With