Is there a more efficient way to get the average value of an array in predefined cells? for example, do I have an array of numbers and an array corresponding to the start and end positions of bin in this array, and I want to just take the average value in these cells? I have a code that does this below, but I wonder how it can be shortened and improved. thank.
from scipy import * from numpy import * def get_bin_mean(a, b_start, b_end): ind_upper = nonzero(a >= b_start)[0] a_upper = a[ind_upper] a_range = a_upper[nonzero(a_upper < b_end)[0]] mean_val = mean(a_range) return mean_val data = rand(100) bins = linspace(0, 1, 10) binned_data = [] n = 0 for n in range(0, len(bins)-1): b_start = bins[n] b_end = bins[n+1] binned_data.append(get_bin_mean(data, b_start, b_end)) print binned_data
python numpy scipy scientific-computing
user248237 May 28 '11 at 17:43 2011-05-28 17:43
source share