平均numpy数组但保留形状 [英] average numpy array but retain shape
本文介绍了平均numpy数组但保留形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Numpy 3轴数组,其元素是3维的.我想将它们取平均值并返回数组的相同形状.正常的均值函数会删除这3个维度,并用平均值代替(如预期的那样):
I have a Numpy 3 axis array whose elements are 3 dimensional. I'd like to average them and return the same shape of the array. The normal average function removes the 3 dimensions and replace it with the average (as expected):
a = np.array([[[0.1, 0.2, 0.3], [0.2, 0.3, 0.4]],
[[0.4, 0.4, 0.4], [0.7, 0.6, 0.8]]], np.float32)
b = np.average(a, axis=2)
# b = [[0.2, 0.3],
# [0.4, 0.7]]
需要结果:
# b = [[[0.2, 0.2, 0.2], [0.3, 0.3, 0.3]],
# [[0.4, 0.4, 0.4], [0.7, 0.7, 0.7]]]
您可以优雅地做到这一点,还是只需要迭代Python中的数组(与强大的Numpy函数相比,它会慢很多).
Can you do this elegantly or do I just have to iterate over the array in Python (which will be a lot slower compared to a powerful Numpy function).
也许可以将np.mean函数的Dtype参数设置为一维数组吗?
Can you set the Dtype argument, for the np.mean function, to a 1D array perhaps?
谢谢.
推荐答案
>>> import numpy as np
>>> a = np.array([[[0.1, 0.2, 0.3], [0.2, 0.3, 0.4]],
... [[0.4, 0.4, 0.4], [0.7, 0.6, 0.8]]], np.float32)
>>> b = np.average(a, axis=2)
>>> b
array([[ 0.2 , 0.29999998],
[ 0.40000001, 0.69999999]], dtype=float32)
>>> c = np.dstack((b, b, b))
>>> c
array([[[ 0.2 , 0.2 , 0.2 ],
[ 0.29999998, 0.29999998, 0.29999998]],
[[ 0.40000001, 0.40000001, 0.40000001],
[ 0.69999999, 0.69999999, 0.69999999]]], dtype=float32)
这篇关于平均numpy数组但保留形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文