I have a big list of lists, something like
import numpy as np
np.array([range(1,1000), range(1,1000), range(1,1000)])
And I'd like to calculate the average of 50 values each in each column. I'd like to get something like:
np.array([[np.mean(range(1,50)), np.mean(range(51,100)), ...], [[np.mean(range(1,50)), np.mean(range(51,100)), ...], ...])
But instead of values from 1-1000 I have several text files with one column each, and I packed them together in the np.array with
average_list = np.array([ np.genfromtxt("1.txt"), np.genfromtxt("2.txt") ])
I tried looping over parts of the list and adding 50 values together, but it doesn't seem to do what I want it to
average_list = np.array([ np.genfromtxt("1.txt"), np.genfromtxt("2.txt") ])
new_list = []
n=100
for i in range(len(average_list)):
for j in range(len(average_list[i])):
while n < j < n+50:
average_list[i,j]+=average_list[i,j+1]
j+=1
new_list.append(average_list[i,j])
print new_list
n+=50
Simple and easy to read solution is to run a map
over the outer list and run a for loop over the indices of the inner loop at every space of 50.
Here's a demo:
length = 3
a = np.array([range(1,10), range(1,10)])
map(lambda y: [np.mean(y[i:i+length]) for i in range(0, len(y), length)], a)
The above code takes the average of every 3 elements
You could also use xrange
if using python2
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