Reputation: 51
I have a list containing lists containing arrays, something like this:
A = [
[
array([[ 1., 4.3, 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
],
[
array([[ 5., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
]
]
So I basically have two 4x4 matrices inside of this thing. Now, the goal is to take the average of these two which I managed to do with:
np.mean([A[0][0],A[1][0]],axis=0)
I also have another matrix B which consists of three 4x4 matrices, and the average would then be something like
np.mean([B[0][0],B[1][0]],B[2][0],axis=0)
I want to generalize this so that I dont have to rewrite the np.mean part each time. So I would probably use the length of A (2) or length of B (3) to construct that, but I'm not sure how to get something like
np.mean(C[0][0],C[1][0],[...][0],[n-1][0],axis=0)
where n is len(C).
How can I implement this? Thanks!
Upvotes: 3
Views: 73
Reputation: 82929
You could just use a list comprehension:
>>> np.mean([A[i][0] for i in range(len(A))], axis=0)
Or shorter, more readable and "pythonic":
>>> np.mean([a[0] for a in A], axis=0)
array([[ 3. , 2.15, 0. , 0. ],
[ 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. ]])
Upvotes: 1