numpy.average()
方法计算沿指定轴的加权平均值。
示例
import numpy as np
# create an array
array1 = np.array([0, 1, 2, 3, 4, 5, 6, 7])
# calculate the average of the array
avg = np.average(array1)
print(avg)
# Output: 3.5
average() 语法
numpy.average()
方法的语法是
numpy.average(array, axis = None, weights = None, returned = False, keepdims = <no value>)
average() 参数
numpy.average()
方法接受以下参数
array
- 包含所需平均值的数字的数组(可以是array_like
)axis
(可选) - 计算平均值的轴(可以是int
或tuple of int
)weights
(可选) - 与 array 中每个值相关联的权重(array_like
)returned
(可选) - 如果为True
,则返回元组(average, sum_of_weights)
,否则仅返回平均值。keepdims
(可选) - 指定是否保留原始数组的形状(bool
)
注意: numpy.average()
的默认值意味着以下几点:
axis = None
- 计算整个数组的平均值。weights = None
- 所有值具有相同的权重(**1**)- 默认情况下,不传递
keepdims
。
average() 返回值
numpy.average()
方法返回数组的加权平均值。
示例 1:查找 ndArray 的平均值
import numpy as np
# create an array
array1 = np.array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
# find the average of entire array
average1 = np.average(array1)
# find the average across axis 0
average2 = np.average(array1, 0)
# find the average across axis 0 and 1
average3 = np.average(array1, (0, 1))
print('\naverage of the entire array:', average1)
print('\naverage across axis 0:\n', average2)
print('\naverage across axis 0 and 1:', average3)
输出
average of the entire array: 3.5 average across axis 0: [[2. 3.] [4. 5.]] average across axis 0 and 1: [3. 4.]
示例 2:为 ndArray 的值指定权重
weights
参数可用于控制输入数组中每个值的重要性。
import numpy as np
array1= np.array([[1, 2, 3],
[4, 5, 6]])
# by default all values have the same weight(1)
result1 = np.average(array1)
# assign variable weights
result2 = np.average(array1, weights = np.arange(0,6,1).reshape(2, 3))
# assign 0 weight to first column
# to get average of 2nd and 3rd column
result3 = np.average(array1, weights = [0, 1, 1], axis = 1)
print('No weights given:', result1)
print('Variable weights:', result2)
print('Average of 2nd and 3rd columns:', result3)
输出
No weights given: 3.5 Variable weights: 4.666666666666667 Average of 2nd and 3rd columns: [2.5 5.5]
当 weights
未分配时,numpy.average()
的作用与 numpy.mean()
相同。
例如,在 result1 中,
average = (1 + 2 + 3 + 4 + 5 + 6) / 6 = 21 / 6 = 3.5
当传递 weights
时,将计算加权平均值。
例如,在 result2 中,
weighted average
= sum(values * weights) / sum(weights)
= (1 * 0 + 2 * 1 + 3 * 2+ 4 * 3 + 5 * 4 + 6 * 5) / (15)
= 4.666666666667
示例 3:使用可选的 keepdims 参数
如果 keepdims
设置为 True
,则结果平均数组的维度数与原始数组相同。
import numpy as np
array1= np.array([[1, 2, 3],
[4, 5, 6]])
# keepdims defaults to False
result1 = np.average(array1, axis = 0)
# pass keepdims as True
result2 = np.average(array1, axis = 0, keepdims = True)
print('Dimensions in original array:',arr.ndim)
print('Without keepdims:', result1, 'with dimensions', result1.ndim)
print('With keepdims:', result2, 'with dimensions', result2.ndim)
输出
Dimensions in original array: 2 Without keepdims: [2.5 3.5 4.5] with dimensions 1 With keepdims: [[2.5 3.5 4.5]] with dimensions 2
示例 4:使用可选的 returned 参数
returned
参数允许指定返回值是仅包含计算出的平均值,还是包含一个元组 (average, sum_of_weights)
。
import numpy as np
array1= np.array([[1, 2, 3],
[4, 5, 6]])
# by default, returned = False
# only average is returned
avg = np.average(array1)
# return the average and sum of weights
avg2,sumWeights = np.average(array1, returned = True)
print('Average:', avg)
print('Average:', avg2, 'with sum of weights:', sumWeights )
输出
Average: 3.5 Average: 3.5 with sum of weights: 6.0
常见问题
当所有权重都为零时会发生什么?
如果所有权重都为零,我们会得到 ZeroDivisionError。
让我们看一个例子。
import numpy as np
array1= np.array([[1, 2, 3],
[4, 5, 6]])
weights = np.zeros(6).reshape(2, 3)
# compute average, by default returned = False, only average returned
avg = np.average(array1, weights = weights)
print('Average:', avg)
输出
ZeroDivisionError: Weights sum to zero, can't be normalized
当权重的长度与数组的长度不同时会发生什么?
当 weights
的长度与沿给定轴的数组长度不同时,我们会得到 TypeError。
让我们看一个例子。
import numpy as np
array1= np.array([1, 2, 3, 4, 5, 6])
weights = np.ones(5)
# the length of array is 6 whereas the length of weights is 5
avg = np.average(array1, weights = weights)
print('Average:', avg)
输出
TypeError: Axis must be specified when shapes of a and weights differ.
如果 weights
的长度与沿指定轴的数组长度不匹配,我们会得到 ValueError。
import numpy as np
array1= np.array([1, 2, 3, 4, 5, 6])
weights = np.ones(5)
# the length of array is 6 whereas the length of weights is 5
avg = np.average(array1, weights = weights, axis = 0)
print('Average:', avg)
输出
ValueError: Length of weights not compatible with specified axis.