本文簡要介紹 python 語言中 numpy.average
的用法。
用法:
numpy.average(a, axis=None, weights=None, returned=False)
計算沿指定軸的加權平均值。
- a: array_like
包含要平均的數據的數組。如果 a 不是數組,則嘗試轉換。
- axis: 無或int 或整數元組,可選
沿其平均的一個或多個軸。默認值,axis=None,將對輸入數組的所有元素進行平均。如果軸為負數,則從最後一個軸計數到第一個軸。
如果axis是整數元組,則在元組中指定的所有軸上執行平均,而不是像以前那樣在單個軸或所有軸上執行。
- weights: 數組,可選
與 a 中的值關聯的權重數組。 a 中的每個值都根據其關聯的權重對平均值做出貢獻。權重數組可以是一維的(在這種情況下,它的長度必須是沿給定軸的 a 的大小)或與 a 具有相同的形狀。如果 weights=None,則假定 a 中的所有數據的權重等於 1。一維計算是:
avg = sum(a * weights) / sum(weights)
對權重的唯一限製是 sum(weights) 不能為 0。
- returned: 布爾型,可選
默認為False.如果True, 元組 (
average
,sum_of_weights) 返回,否則隻返回平均值。如果權重=無,sum_of_weights等於取平均值的元素數量。
- retval, [sum_of_weights]: array_type 或雙
返回沿指定軸的平均值。什麽時候返回是True,返回一個元組,其中平均值作為第一個元素,權重之和作為第二個元素。sum_of_weights與逆轉錄.結果 dtype 遵循一般模式。如果權重為無,結果 dtype 將是a, 或者
float64
如果a是積分。否則,如果權重不是 None 並且a是非整數的,結果類型將是能夠表示兩者值的最低精度類型a和權重.如果a恰好是整數,之前的規則仍然適用,但結果 dtype 至少是float64
.
- ZeroDivisionError
當沿軸的所有權重為零時。請參閱
numpy.ma.average
以了解對此類錯誤具有魯棒性的版本。- TypeError
當一維權重的長度與沿軸的形狀不同時。
參數:
返回:
拋出:
例子:
>>> data = np.arange(1, 5) >>> data array([1, 2, 3, 4]) >>> np.average(data) 2.5 >>> np.average(np.arange(1, 11), weights=np.arange(10, 0, -1)) 4.0
>>> data = np.arange(6).reshape((3,2)) >>> data array([[0, 1], [2, 3], [4, 5]]) >>> np.average(data, axis=1, weights=[1./4, 3./4]) array([0.75, 2.75, 4.75]) >>> np.average(data, weights=[1./4, 3./4]) Traceback (most recent call last): ... TypeError: Axis must be specified when shapes of a and weights differ.
>>> a = np.ones(5, dtype=np.float128) >>> w = np.ones(5, dtype=np.complex64) >>> avg = np.average(a, weights=w) >>> print(avg.dtype) complex256
相關用法
- Python numpy asscalar用法及代碼示例
- Python numpy any用法及代碼示例
- Python numpy ascontiguousarray用法及代碼示例
- Python numpy asarray_chkfinite用法及代碼示例
- Python numpy argpartition用法及代碼示例
- Python numpy arctan用法及代碼示例
- Python numpy array用法及代碼示例
- Python numpy array_repr用法及代碼示例
- Python numpy arccos用法及代碼示例
- Python numpy all用法及代碼示例
- Python numpy add用法及代碼示例
- Python numpy around用法及代碼示例
- Python numpy array2string用法及代碼示例
- Python numpy atleast_1d用法及代碼示例
- Python numpy asanyarray用法及代碼示例
- Python numpy arctan2用法及代碼示例
- Python numpy angle用法及代碼示例
- Python numpy arctanh用法及代碼示例
- Python numpy apply_over_axes用法及代碼示例
- Python numpy arccosh用法及代碼示例
- Python numpy arange用法及代碼示例
- Python numpy argsort用法及代碼示例
- Python numpy asarray用法及代碼示例
- Python numpy array_equiv用法及代碼示例
- Python numpy apply_along_axis用法及代碼示例
注:本文由純淨天空篩選整理自numpy.org大神的英文原創作品 numpy.average。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。