Double Summation in Python

爱⌒轻易说出口 提交于 2019-12-12 11:07:46

问题


I am trying to write a code to conduct a double summation (see pic)

in which; M is the subjects, N is the Trials, Yijt is the measured wave form data (3d array)

so far I have; Given Y is the data arranged as Y[subjects, trials, time]

# ranges:
I = len(Y)
J = len(Y[0])

Y_i_vals = 0

for i in range(M):
    for j in range(N):
        Y_i_vals = Y_i_vals +Y[i][j]
Yt = (1.0/(M*N)) * Y_i_vals

this doesnt seem the most effective way to do this, nor am i certain it is giving the correct result.


回答1:


If you're using numpy just do

np.mean(Y)

Also, it's good to add sample input and expected output data to your question.

If you want means for each t you can do np.mean(np.mean(a, axis=0), axis=0) , or as noted by @ophion you can shorten this to np.mean(a, axis=(0, 1)) in newer (1.71 and on) versions of NumPy.




回答2:


When it comes to simple double summations like in your case, it's nice to use numpy's einsum:

np.einsum('tij -> t', Y) / (M*N)



回答3:


To add a more general answer to your question:

You can code a double summation with the help of python list comprehension.

Yt = (1.0/(M*N)) * sum([Y[i][j] for i in range(M) for j in range(N)])


来源:https://stackoverflow.com/questions/19274813/double-summation-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!