计算给定 NumPy 数组的加权平均值
在 NumPy 中,我们可以通过两种方法计算给定数组的权重,第一种方法是借助 numpy.average()函数,我们在参数中传递权重数组。第二种方法是通过数学计算,首先我们将权重数组总和与权重数组相除,然后与给定数组相乘以计算该数组的总和。
方法一:使用 numpy.average() 方法
示例 1:
Python
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)
Python
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)
Python
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)
Python
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.1666666666666665
示例 2:
Python
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
方法二:使用数学运算
示例 1:
Python
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:
Python
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