計算給定 NumPy 陣列的加權平均值
加權平均是一種平均數型別,其中每個陣列元素在計算資料元素的平均值之前將乘以一個權重因子。每個資料點的權重決定了它對所有整體平均值的貢獻。
計算加權平均值
這用於計算投資組合價值中股票的平均價格。加權平均值的數學公式如下所示。
weighted_average = (w1 * x1 + w2 * x2 + ... + wn * xn) / (w1 + w2 + ... + wn)
其中:
x1, x2, …..,xn 是給定的資料點
w1, w2, ……, wn 分別是乘以每個資料點的加權平均值
n 是元素的總數
NumPy 陣列的加權平均值
在 Python 中,NumPy 庫提供 average() 函式來計算給定陣列元素的加權平均值。
語法
以下是查詢給定陣列元素的加權平均值的語法:
numpy.average(array, weights = weights)
其中:
Array 是輸入陣列
weights 是在計算平均值之前要乘以陣列元素的權重值。
示例
為了找到給定陣列的加權平均值,我們必須將陣列和權重作為輸入引數傳遞。在這裡,我們傳遞的是二維陣列的元素和權重:
import numpy as np
a = np.array([[34,23],[90,34]])
weights = np.array([[2,3],[5,7]])
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
avg = np.average(a)
print("The average of the given 2-d array:",avg)
weg = np.average(a,weights = weights)
print("weighted average of the array:",weg)
輸出
The input array: [[34 23] [90 34]] The dimension of the array: 2 The average of the given 2-d array: 45.25 weighted average of the array: 48.529411764705884
示例
在下面的示例中,我們嘗試計算一維陣列的加權平均值:
import numpy as np
a = np.array([3,4,2,3,90,34])
weights = np.array([2,3,1,5,7,6])
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
avg = np.average(a)
print("The average of the given 1-d array:",avg)
weg = np.average(a,weights = weights)
print("weighted average of the array:",weg)
輸出
The input array: [ 3 4 2 3 90 34] The dimension of the array: 1 The average of the given 1-d array: 22.666666666666668 weighted average of the array: 36.208333333333336
示例
在這個例子中,我們使用 average() 函式計算三維陣列的加權平均值:
import numpy as np
a = np.array([[[3,4],[2,3]],[[90,34],[78,23]]])
weights = np.array([[[3,4],[2,3]],[[90,34],[78,23]]])
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
avg = np.average(a)
print("The average of the given 3-d array:",avg)
weg = np.average(a,weights = weights)
print("weighted average of the array:",weg)
輸出
The input array: [[[ 3 4] [ 2 3]] [[90 34] [78 23]]] The dimension of the array: 3 The average of the given 3-d array: 29.625 weighted average of the array: 67.11814345991561
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP