Home > front end >  averaging every nth element of multiple lists
averaging every nth element of multiple lists

Time:02-20

I have 4 lists of the same length and would like to average every nth element across the lists and make a new list out of these averaged values. As an example:

y1 = [1, 2, 2, 4, 5]
y2 = [3, 6, 9, 12, 0]
y3 = [2, 3, 4, 5, 6]
y4 = [2, 1, 5, 7, 9]

The expected result should be:

y1234  = [2, 3, 5, 7, 5]

How can I do this?

CodePudding user response:

You can do it with a list comprehension:

y1 = [1, 2, 2, 4, 5]
y2 = [3, 6, 9, 12, 0]
y3 = [2, 3, 4, 5, 6]
y4 = [2, 1, 5, 7, 9]

n_lists = 4

y1234 = [int(sum(x)/n_lists) for x in zip(y1, y2, y3, y4)]

Note that in your example the last average would be 4.

zip returns a tuple that you can then send to the sum. Make sure that the conversion with int is what you want (not round or floor etc.)

CodePudding user response:

You can use numpy.mean

np.array([y1, y2, y3, y4]).mean(axis=0)
  • Related