Given a numpy array M of shape (r, c) e.g.
M = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
[13, 14, 15]]) # r = 5; c = 3
and a one-dimensional array a of length r, containing integers that can vary from 0 to k-1, e.g.
a = np.array([0, 0, 2, 1, 0]) # k = 4
I want to use the values in a to select rows from M to get an intermediate result like this:
array([
[[1, 2, 3], [4, 5, 6], [13, 14, 15]] # rows of M where a == 0
[[10, 11, 12]], # rows of M where a == 1
[[7, 8, 9]] # rows of M where a == 2
[] # rows of M where a == 3 (there are none)
])
(I don't need this intermediate array, but am just showing it for illustration.) The returned result would be a (k, c) array with the column-wise means from this array:
array([[ 6., 7., 8.], # means where a == 0
[10., 11., 12.], # means where a == 1
[ 7., 8., 9.], # etc.
[nan, nan, nan]])
I can do this with
np.array([M[a == i].mean(axis=0) for i in range(k)])
but is there a way (hopefully faster for large r and k) that purely uses numpy methods instead of using a for loop to make a list (which will then have to be converted back to an array)?





