Python 两个 Numpy 数组中的平均值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18461623/
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
Average values in two Numpy arrays
提问by Forde
Given two ndarrays
给定两个 ndarray
old_set = [[0, 1], [4, 5]]
new_set = [[2, 7], [0, 1]]
I'm looking to get the mean of the respective values between the two arrays so that the data ends up something like:
我正在寻找两个数组之间各自值的平均值,以便数据最终类似于:
end_data = [[1, 4], [2, 3]]
basically it would apply something like
基本上它会应用类似的东西
for i in len(old_set):
end_data[i] = (old_set[i]+new_set[i])/2
But I'm unsure what syntax to use.. Thanks for the help in advance!
但我不确定要使用什么语法.. 提前感谢您的帮助!
采纳答案by falsetru
>>> import numpy as np
>>> old_set = [[0, 1], [4, 5]]
>>> new_set = [[2, 7], [0, 1]]
>>> (np.array(old_set) + np.array(new_set)) / 2.0
array([[1., 4.],
[2., 3.]])
回答by Saullo G. P. Castro
You can create a 3D array containing your 2D arrays to be averaged, then average along axis=0using np.meanor np.average(the latter allows for weighted averages):
您可以创建一个包含要平均的 2D 数组的 3D 数组,然后axis=0使用np.meanor进行平均np.average(后者允许加权平均):
np.mean( np.array([ old_set, new_set ]), axis=0 )
This averaging scheme can be applied to any (n)-dimensional array, because the created (n+1)-dimensional array will always contain the original arrays to be averaged along its axis=0.
这种平均方案可以应用于任(n)何一维数组,因为创建的一(n+1)维数组将始终包含要沿其平均的原始数组axis=0。
回答by G M
Using numpy.average
使用 numpy.average
Also numpy.averagecan be used with the same syntax:
也numpy.average可以使用相同的语法:
import numpy as np
a = np.array([np.arange(0,9).reshape(3,3),np.arange(9,18).reshape(3,3)])
averaged_array = np.average(a,axis=0)
The advantage of numpy.average compared to numpy.meanis the possibility to use also the weights parameter as an array of the same shape:
与 numpy.average 相比的优点numpy.mean是可以将 weights 参数用作相同形状的数组:
weighta = np.empty((3,3))
weightb = np.empty((3,3))
weights = np.array([weighta.fill(0.5),weightb.fill(0.8) ])
np.average(a,axis=0,weights=weights)
If you use masked arrays consider also using numpy.ma.averagebecause numpy.averagedon't deal with them.
如果您使用掩码数组,请考虑使用,numpy.ma.average因为numpy.average不要处理它们。
回答by Gabriel123
As previously said, your solution does not work because of the nested lists (2D matrix). Staying away from numpy methods, and if you want to use nested for-loops, you can try something like:
如前所述,由于嵌套列表(二维矩阵),您的解决方案不起作用。远离 numpy 方法,如果您想使用嵌套的 for 循环,您可以尝试以下操作:
old_set = [[0, 1], [4, 5]]
new_set = [[2, 7], [0, 1]]
ave_set = []
for i in range(len(old_set)):
row = []
for j in range(len(old_set[0])):
row.append( ( old_set[i][j] + new_set[i][j] ) / 2 )
ave_set.append(row)
print(ave_set) # returns [[1, 4], [2, 3]]

