本文介绍Python扩展库numpy的函数average()的用法。
>>> import numpy as np
# 创建二维矩阵
>>> x = np.matrix([[1,2,3], [4,5,6]])
# 设置权重
>>> w1 = [0.3, 0.7]
# 纵向计算加权平均
>>> np.average(x, axis=0, weights=w1)
matrix([[ 3.1, 4.1, 5.1]])
>>> w2 = [0.3, 0.3, 0.4]
# 横向计算加权平均
>>> np.average(x, axis=1, weights=w2)
matrix([[ 2.1],
[ 5.1]])
>>> np.average(x, axis=1, weights=w2, returned=True)
(matrix([[ 2.1],
[ 5.1]]), array([[ 1.],
[ 1.]]))