Reputation: 3043
I want to use information from entries in a (python) list of lists to average rows of a numpy array. For example, consider the following:
LoL = [[], [0, 1, 2, 4], [3, 5], [], [6]] #List of lists
arr = np.array([[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5], [6, 6, 6, 6]]) #Numpy array
print arr
[[0 0 0 0]
[1 1 1 1]
[2 2 2 2]
[3 3 3 3]
[4 4 4 4]
[5 5 5 5]
[6 6 6 6]]
For the above list of lists (LoL
) and numpy array (arr
), I would like rows [0, 1, 2, 4]
of arr
to get averaged, rows [3, 5]
of arr
to get averaged between themselves and row [6]
to stay in its original form. The transformed array (arr_new
) should look like the following:
arr_new = np.array([[1.75, 1.75, 1.75, 1.75], [4.0, 4.0, 4.0, 4.0] , [6.0, 6.0, 6.0, 6.0]])
print arr_new
[[1.75 1.75 1.75 1.75]
[4. 4. 4. 4. ]
[6. 6. 6. 6. ]]
What is the most elegant way to do this?
Upvotes: 0
Views: 116
Reputation: 51165
Due to the inconsistent shape in your list
of list
's, there isn't an elegant way to perform a single operation, however looping is an option and should still be efficient, since it only scales with the size of LoL
:
np.stack([np.mean(arr[el], 0) for el in LoL if el])
array([[1.75, 1.75, 1.75, 1.75],
[4. , 4. , 4. , 4. ],
[6. , 6. , 6. , 6. ]])
Upvotes: 1