Home > front end >  In a list of lists, how can I find the mean of the values for each subindex?
In a list of lists, how can I find the mean of the values for each subindex?

Time:02-13

I want to find the average of each index in a list of lists. Say I have this:

import statistics

my_list = [[1, 2, 3], [4, 5], [7, 8, 9], [10, 11]]

I want to find the average of each interior list index, so:

  • for index 0, I would have the value of (1 4 7 10)/4
  • for index 1, I would have the value of (2 5 8 11)/4
  • for index 2, I would have the value of (3 9)/2

and so on. How can I do this? Note that I do not need to save the values, just print them as they are computed.

CodePudding user response:

You can use the package pandas to achieve your goal.

#import pandas
import pandas as pd
#you list
my_list = [[1, 2, 3], [4, 5], [7, 8, 9], [10, 11]]
#Create a DataFrame from your list
df = pd.DataFrame(my_list)
#mean for each row
df.mean()

CodePudding user response:

If you prefer vanilla python, you can try the following:

my_list = [[1, 2, 3], [4, 5], [7, 8, 9], [10, 11]]

d = {}

for elem in my_list:
    for i in range(len(elem)):
        if i in d:
            d[i].append(elem[i])
        else:
            d[i] = [elem[i]]

for k,v in d.items():
    print(f'The average of idx {k} is {sum(v) / len(v)}')
    

Output:

The average of idx 0 is 5.5
The average of idx 1 is 6.5
The average of idx 2 is 6.0

CodePudding user response:

You want to use itertools.zip_longest. You can group together by index, filter out any None elements returns by zip_longest, and then take the mean.

from itertools import zip_longest
from statistics import mean

for i, group in enumerate(zip_longest(*my_list)):
    print(f'Index {i} mean:', mean(filter(lambda x: x is not None, group)))

# prints:
Index 0 mean: 5.5
Index 1 mean: 6.5
Index 2 mean: 6
  • Related