计算一个给定的NumPy数组的加权平均数
在NumPy中,我们可以通过两种方法计算一个给定数组的加权,第一种方法是在numpy.average()函数的帮助下,我们在参数中传递权重数组。第二种方法是通过数学计算,首先我们从权重数组中除以权重数组的总和,然后与给定数组相乘来计算该数组的总和。
方法1:使用numpy.average()方法
示例 1:
import numpy as np
# Original array
array = np.arange(5)
print(array)
weights = np.arange(10, 15)
print(weights)
# Weighted average of the given array
res1 = np.average(array, weights=weights)
print(res1)
输出:
[0 1 2 3 4]
[10 11 12 13 14]
2.1666666666666665
示例 2:
import numpy as np
# Original array
array = np.arange(2, 7)
print(array)
weights = np.arange(2, 7)
print(weights)
# Weighted average of the given array
res1 = np.average(array, weights=weights)
print(res1)
输出:
[2 3 4 5 6]
[2 3 4 5 6]
4.5
方法2:使用数学运算
示例 1:
import numpy as np
# Original array
array = np.arange(2, 7)
print(array)
weights = np.arange(2, 7)
print(weights)
# Weighted average of the given array
res2 = (array*(weights/weights.sum())).sum()
print(res2)
输出:
[2 3 4 5 6]
[2 3 4 5 6]
4.5
示例 2:
import numpy as np
# Original array
array = np.arange(5)
print(array)
weights = np.arange(10, 15)
print(weights)
# Weighted average of the given array
res2 = (array*(weights/weights.sum())).sum()
print(res2)
输出:
[0 1 2 3 4]
[10 11 12 13 14]
2.166666666666667