本文介绍了Python/NumPy中用于计算均值的元素排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的一维列表如下:
data = [1,5,9,13,
2,6,10,14,
3,7,11,15,
4,8,12,16]
我要列出以下元组,并分别计算每个元组的平均值.
I want to make the following list of tuples, and calculate mean of each tuple separately.
[(1,5,2,6), (3,7,4,8), (9,13,10,14), (11,15,12,16)]
预期结果应该是:
[3.5, 5.5, 11.5, 13.5]
最简单的方法是什么?
推荐答案
将数据放入形状为(2,2,2,2,2)的4-d numpy数组中,然后取该数组在轴1和轴上的均值3:
Put the data into a 4-d numpy array with shape (2, 2, 2, 2), then take the mean of that array over axes 1 and 3:
In [25]: data
Out[25]: [1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16]
In [26]: a = np.array(data).reshape(2, 2, 2, 2)
In [27]: a
Out[27]:
array([[[[ 1, 5],
[ 9, 13]],
[[ 2, 6],
[10, 14]]],
[[[ 3, 7],
[11, 15]],
[[ 4, 8],
[12, 16]]]])
In [28]: a.mean(axis=(1, 3))
Out[28]:
array([[ 3.5, 11.5],
[ 5.5, 13.5]])
如果需要最终结果作为一维数组,则可以使用ravel()
方法:
You can use the ravel()
method if you need the final result as a 1-d array:
In [31]: a.mean(axis=(1, 3)).ravel()
Out[31]: array([ 3.5, 11.5, 5.5, 13.5])
请参见如何我可以向量化numpy数组的2x2子数组的平均值吗?有一个类似的问题.
See How can I vectorize the averaging of 2x2 sub-arrays of numpy array? for a similar question.
这篇关于Python/NumPy中用于计算均值的元素排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!