Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average over parts in list of lists

Tags:

python

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
like image 561
Tolotos Avatar asked Sep 28 '22 06:09

Tolotos


1 Answers

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

like image 82
AbdealiJK Avatar answered Oct 06 '22 02:10

AbdealiJK