The average number of parts in a list of lists

I have a large list of lists, something like

import numpy as np np.array([range(1,1000), range(1,1000), range(1,1000)]) 

And I would like to calculate the average of 50 values ​​in each column. I would 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 put them together in np.array with

 average_list = np.array([ np.genfromtxt("1.txt"), np.genfromtxt("2.txt") ]) 

I tried iterating over parts of the list and adding 50 values ​​together, but it doesn't seem to do what I want

 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 
+5
source share
2 answers

A simple and understandable solution is to start map on the external list and start the for loop on the indices of the inner loop in each space 50.

Here is 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 an average of every 3 elements. You can also use xrange if using python2

+4
source

You can reshape array first reshape that each line is one of a group of 50 elements, then apply np.mean to each of these lines, and then change shape 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]]) 
0
source

All Articles