在二维数组跨维度计算平均 [英] Calculate mean across dimension in a 2D array

查看:162
本文介绍了在二维数组跨维度计算平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组 A 是这样的:

I have an array a like this:

a=[]
a.append([40,10])
a.append([50,11])

所以它看起来是这样的:

so it looks like this:

 >>> a
[[40, 10], [50, 11]]

我需要单独计算平均每个维度,结果应该是这样的:

I need to calculate the mean for each dimension separately, the result should be this:

[45,10.5]

45 是平均 A [*] [0] 10.5 的'平均一个[*] [1]。

45 being the mean of a[*][0] and 10.5 the mean of `a[*][1].

什么是解决这个无需进入循环的最优雅的方式?

What is the most elegant way of solving this without going to a loop?

推荐答案

a.mean()需要一个参数:

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

这篇关于在二维数组跨维度计算平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆