Question

Assuming an (1-d) array, is it possible to calculate the average on given groups of diifferent size without looping? Instead of

avgs = [One_d_array[groups[i]].mean() for i in range(len(groups))]

Something like

avgs = np.mean(One_d_array, groups)

Basically I want to do this:

M = np.arange(10000)
np.random.shuffle(M)
M.resize(100,100)
groups = np.random.randint(1, 10, 100)

def means(M, groups):
    means = []
    for i, label in enumerate(groups):
        means.extend([M[i][groups == j].mean() for j in set(p).difference([label])])
    return means

This runs at

%timeit means(M, groups)
100 loops, best of 3: 12.2 ms per loop

Speed up of 10 times or so would be already great

Was it helpful?

Solution

Whether you see a loop or not, there is a loop.
Here's one way, but the loop is simply hidden in the call to map:

In [10]: import numpy as np

In [11]: groups = [[1,2],[3,4,5]]

In [12]: map(np.mean, groups)
Out[12]: [1.5, 4.0]

OTHER TIPS

Another hidden loop is the use of np.vectorize:

>>> x = np.array([1,2,3,4,5])
>>> groups = [[0,1,2], [3,4]]
>>> np.vectorize(lambda group: np.mean(x[group]), otypes=[float])(groups)
array([ 2. , 4.5])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top