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

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

问题描述

我有一个这样的数组 a:

I have an array a 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]

45a[*][0] 的平均值,10.5a[*][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 using a loop?

推荐答案

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

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

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