Python 的 numpy 模塊提供了一個名為 numpy.average() 的函數,用於計算沿指定軸的加權平均值。
用法:
numpy.average(a, axis=None, weights=None, returned=False)
參數:
x:數組
此參數定義了我們要計算其元素平均值的源數組。如果 'x' 是一個數組,則將嘗試轉換。
軸:整數或無或整數元組(可選)
此參數定義了將沿其計算平均值的軸。默認情況下,軸設置為無,這將計算源數組所有元素的平均值。當軸的值為負時,從結束軸開始計數到開始軸。
權重:數組(可選)
此參數定義一個包含與數組值關聯的權重的數組。數組元素的每個值一起根據其關聯的權重進行平均值。加權數組可以是一維的,也可以是與輸入數組相同的形狀。當沒有與數組元素關聯的權重時,所有元素的權重將被視為 1。
返回:布爾(可選)
默認情況下,此參數設置為 False。如果我們將其設置為 True,則返回一個由 average 和 sum_of_weights 組成的元組。如果為 False,則返回平均值。如果沒有權重值,則加權和等於元素的數量。
返回值:
retval, [sum_of_weights]:array_type 或雙倍
此函數返回取決於返回參數的平均值或平均值和 sum_of_weights。
raise :
零分誤差
當沿軸的所有權重都設置為零時,會引發此錯誤。
TypeError
當加權數組的長度與輸入數組的形狀不同時,會引發此錯誤。
範例1:
import numpy as np
data = list(range(1,6))
output=np.average(data)
data
output
輸出:
[1, 2, 3, 4, 5] 3.0
在上麵的代碼中:
- 我們已經導入了別名為 np.
- 我們創建了一個元素列表 'data'。
- 我們已經聲明了變量 'output' 並賦值了 average() 函數的返回值。
- 我們已經在函數中傳遞了列表 'data'。
- 最後,我們嘗試打印 'data' 和 'output'
在輸出中,它顯示了列表元素的平均值。
範例2:
import numpy as np
output=np.average(range(1,16), weights=range(15,0,-1))
output
輸出:
5.666666666666667
範例3:
import numpy as np
data=np.arange(12).reshape((4,3))
output = np.average(data, axis=1, weights=[1./4, 3./4, 5./4])
data
output
輸出:
array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) array([ 1.44444444, 4.44444444, 7.44444444, 10.44444444])
在上麵的代碼中:
- 我們已經導入了別名為 np.
- 我們使用 arange() 和 np.reshape() 函數創建了一個數組 'data'。
- 我們已經聲明了變量 'output' 並賦值了 average() 函數的返回值。
- 我們在函數中傳遞了數組'data',設置axis為1,並給數組加權。
- 最後,我們嘗試打印 'data' 和 'output'
在輸出中,它顯示了數組中每列元素的平均值。
範例4:
import numpy as np
data=np.arange(12).reshape((4,3))
data
np.average(data, weights=[1./4, 3./4, 5./4])
輸出:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\numpy\lib\function_base.py", line 406, in average
"Axis must be specified when shapes of data and weights."
TypeError:Axis must be specified when shapes of data and weights differ.
注意:輸出顯示類型錯誤:'當數據和權重的形狀不同時必須指定軸',因為 'weights' 數組的形狀與輸入數組 'data' 的形狀不同。
相關用法
- Python numpy.atleast_2d()用法及代碼示例
- Python numpy.angle()用法及代碼示例
- Python numpy.asscalar()用法及代碼示例
- Python numpy.asmatrix()用法及代碼示例
- Python numpy.absolute()用法及代碼示例
- Python numpy.any()用法及代碼示例
- Python numpy.argwhere()用法及代碼示例
- Python numpy.arccosh()用法及代碼示例
- Python numpy.amax()用法及代碼示例
- Python numpy.arcsinh()用法及代碼示例
- Python numpy.array_repr()用法及代碼示例
- Python numpy.array_str()用法及代碼示例
- Python numpy.apply_along_axis()用法及代碼示例
- Python numpy.argmax()用法及代碼示例
- Python numpy.arctan()用法及代碼示例
- Python numpy.around()用法及代碼示例
- Python numpy.array()用法及代碼示例
- Python numpy.arccos()用法及代碼示例
- Python numpy.all()用法及代碼示例
- Python numpy.allclose()用法及代碼示例
注:本文由純淨天空篩選整理自 numpy.average() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。