NumPy 计算给定数组的加权平均值

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)

在下面例子中,我们计算给定数组的加权平均值,需要将数组和权重作为输入参数传递。这里,我们传递的是一个二维数组的元素和权重。

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()函数计算3-D数组的加权平均值 –

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程