tara tandel
tara tandel

Reputation: 550

Mean of multi level nested lists in python

I have a list like this

b= [
    [
        [[1],[2],[3]],
        [[4],[5],[6]],
        [[7],[8],[9]]
        ],
    [
        [[1],[2],[3]],
        [[4],[5],[6]],
        [[7],[8],[9]]
        ], 
    [
        [[1],[2],[3]],
        [[4],[5],[6]],
        [[7],[8],[9]]
        ]
]

this list can have up to 10 nested lists (here we only see 3). I want to average this list in such a way that in the end, I have

b= [
        [[1],[2],[3]],
        [[4],[5],[6]],
        [[7],[8],[9]]
        ]

notice that the first element of the first nested list is average among all of the other nested elements. to be more precise all the ones should be average together. then all the 2s should be averaged together and this goes on until 9. and at the end, I have to preserve the structure as I showed above.

Upvotes: 1

Views: 466

Answers (1)

tomjn
tomjn

Reputation: 5390

numpy is your friend in cases like this. If we convert b into a np.array it has a shape of (3, 3, 3, 1). The 1 here refers to the length of your inner lists. We can the use the mean method along the first axis to get your answer (you can convert this back to a list but you might want to stick with numpy if you are doing more analysis).

import numpy as np

answer = np.array(b).mean(axis=0).tolist()

where answer is

[
 [[1.0], [2.0], [3.0]],
 [[4.0], [5.0], [6.0]], 
 [[7.0], [8.0], [9.0]]
]

If you want to keep the answer as integers then you can explicitly request the array to be of int type:

np.array(b).mean(axis=0).astype(int).tolist()

Upvotes: 4

Related Questions