本文介绍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.]]))
相关阅读:
--------我是分割线---------
新书发布,《Python程序设计开发宝典》正式出版,过几天全面上架之后会在公众号搞个转发集赞送书的活动,敬请期待。