简体   繁体   中英

Find mean of nth item in list of lists in Python

after a lot of searching I haven't been able to find the answer to what seems like a simple question.

I have some code that is doing a Monte Carlo simulation and storing the results in a nested list. Here are the results I generate from a 10-trial simulation:

[[1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], [0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0], [1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1]]

Where I'm stuck is I'd like to find the mean of the 0th item in each list, the 1st item, and so on. I generally use numpy.mean for this, but how do I instruct it to only average the nth item?

You can use np.mean with axis=0 :

lst = [[1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], [0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0], [1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1]]
np.mean(lst, axis=0)
# array([ 0.9,  1. ,  0.8,  0.9,  0.6,  0.8,  0.5,  0.7,  0.8,  0.5,  0.7, 0.5,  0.6])

If I understood the question well, the answer is the same as @Psidom proposed but over axis=1 . Also, you may need to convert it to a numpy array beforehand:

lst = np.array([[1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1], 
                [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], # and so on...)
np.mean(lst, axis=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM