-1

I am new to Python. I am enumerating through a large list of data, as shown below, and would like to find the mean of every line.

for index, line in enumerate (data):
    #calculate the mean
   

However, the lines of this particular set of data are as such:

[array([[2.3325655e-10, 2.4973504e-10],
       [1.3025138e-10, 1.3025231e-10]], dtype=float32)].

I would like to find the mean of both 2x1s separately, then the average of both means, so it outputs a single number. Thanks in advance.

Ethan
  • 876
  • 8
  • 18
  • 34
  • What is the usual format of the data? Are there any exceptions? – XxJames07- Aug 29 '22 at 20:22
  • I'm sorry I'm not sure what you mean? The format of the data is as presented in the question. – chemengdev Aug 29 '22 at 20:47
  • 1
    So you have something like `arr = numpy.array([[2.3325655e-10, 2.4973504e-10], [1.3025138e-10, 1.3025231e-10]])`? Then you could do `mean = arr.mean(1).mean()`. – Timus Aug 29 '22 at 21:14

1 Answers1

0

You probably do not need to enumerate through the list to achieve what you want. You can do it in two steps using list comprehension.

For example,

data = [[2.3325655e-10, 2.4973504e-10],
       [1.3025138e-10, 1.3025231e-10]]
# Calculate the average for 2X1s or each row
avgs_along_x = [sum(line)/len(line) for line in data]
# Calculate the average along y
avg_along_y = sum(avgs_along_x)/len(avgs_along_x)

There are other ways to calculate the mean of a list in python. You can read about them here.

If you are using numpy this can be done in one line.

import numpy as np
np.average(data, 1) # calculate the mean along x-axes denoted as 1
# To get what you want, we can pass tuples of axes.
np.average(data, (1,0))

Amit
  • 61
  • 1
  • 2