Python 计算二维数组中跨维度的平均值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15819980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate mean across dimension in a 2D array
提问by otmezger
I have an array alike this:
我有一个a这样的数组:
a = [[40, 10], [50, 11]]
I need to calculate the mean for each dimension separately, the result should be this:
我需要分别计算每个维度的平均值,结果应该是这样的:
[45, 10.5]
45being the mean of a[*][0]and 10.5the mean of a[*][1].
45是 的均值a[*][0]和10.5的均值a[*][1]。
What is the most elegant way of solving this without using a loop?
在不使用循环的情况下解决这个问题的最优雅的方法是什么?
回答by askewchan
a.mean()takes an axisargument:
a.mean()接受一个axis论点:
In [1]: import numpy as np
In [2]: a = np.array([[40, 10], [50, 11]])
In [3]: a.mean(axis=1) # to take the mean of each row
Out[3]: array([ 25. , 30.5])
In [4]: a.mean(axis=0) # to take the mean of each col
Out[4]: array([ 45. , 10.5])
Or, as a standalone function:
或者,作为一个独立的函数:
In [5]: np.mean(a, axis=1)
Out[5]: array([ 25. , 30.5])
The reason your slicing wasn't working is because this is the syntax for slicing:
您的切片不起作用的原因是因为这是切片的语法:
In [6]: a[:,0].mean() # first column
Out[6]: 45.0
In [7]: a[:,1].mean() # second column
Out[7]: 10.5
回答by NPE
回答by Andrew Clark
Here is a non-numpy solution:
这是一个非numpy的解决方案:
>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]

