Reputation: 53
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
Upvotes: 5
Views: 243
Reputation: 3347
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
Upvotes: 4
Reputation: 82939
You can first reshape
the array so that each row is one of the groups of 50 elements, and then apply np.mean
to each of those rows, then reshape again.
>>> a = np.array([range(1000), range(1000), range(1000)])
>>> b = np.reshape(a, (60, 50))
>>> c = np.apply_along_axis(np.mean, 1, b)
>>> np.reshape(c, (3, 20))
array([[ 24.5, 74.5, 124.5, 174.5, 224.5, 274.5, 324.5, 374.5,
424.5, 474.5, 524.5, 574.5, 624.5, 674.5, 724.5, 774.5,
824.5, 874.5, 924.5, 974.5],
[ 24.5, 74.5, 124.5, 174.5, 224.5, 274.5, 324.5, 374.5,
424.5, 474.5, 524.5, 574.5, 624.5, 674.5, 724.5, 774.5,
824.5, 874.5, 924.5, 974.5],
[ 24.5, 74.5, 124.5, 174.5, 224.5, 274.5, 324.5, 374.5,
424.5, 474.5, 524.5, 574.5, 624.5, 674.5, 724.5, 774.5,
824.5, 874.5, 924.5, 974.5]])
Upvotes: 0