NumPy mean()
函数
在本教程中,我们将介绍 NumPy 库的numpy.mean()
功能。
只需将数组的所有项目相加并将除以数组元素的总数,就可以很容易地计算出平均值。
NumPy 库中的
numpy.mean()
函数用于计算数组中沿指定轴的算术平均值。所以这个函数主要是返回数组元素的平均值。默认情况下,平均值是在展平的数组上计算的,否则,它将在指定的轴上计算。
numpy.mean()
的语法:
使用该函数所需的语法如下:
numpy.mean(a, axis=None, out, dtype)
参数:
下面是该函数使用的参数描述:
a 该参数用于指示输入数组。
轴 这个参数用来表示我们要计算中位数的轴。默认情况下,输入数组被展平(即在所有轴上工作)。这里,对于轴的值,轴= 0 表示沿列的,轴= 1 表示沿行工作的。
out 这是一个可选的参数,用于指示我们想要放置结果的可选数组。数组必须具有与预期输出相同的维度。
数据类型 这是一个可选的参数,用于在计算平均值时指示我们想要的类型。
返回值:
该函数主要返回数组的算术平均值(如果轴为无,则返回标量值)或沿指定轴有平均值的数组。
例 1:
下面给出了一个基本示例,向您展示了该功能的工作原理:
import numpy as np
x= [80, 23, 17, 1, 39]
print("The Input array is : ")
print(x)
print("The mean of the array is : ")
print(np.mean(x))
输入数组为: 【80,23,17,1,39】 数组的平均值为: 32.0
例 2:
现在,我们将在二维数组上应用此函数,并将检查输出:
import numpy as np
p = [[14, 19, 12, 34, 43], [16, 8, 28, 8, 20], [25, 5, 55, 1, 2]]
# calculating mean of the flattened array
print("\nThe mean of the array when axis = None : ")
print(np.mean(p))
# calculating the mean along the axis = 0
print("\nThe mean of the array when axis = 0 : ")
print(np.mean(p, axis = 0))
# calculating the mean along the axis = 1
print("\nThe mean of the array when axis = 1 : ")
print(np.mean(p, axis = 1))
out_arr = np.arange(3)
print("\nout_arr : ", out_arr)
print("mean of arr, axis = 1 : ")
print(np.mean(p, axis = 1, out = out_arr))
当轴=无时数组的平均值: 19.33333333333332
当轴= 0 时数组的平均值: 【18.3333333333 10.666666731.666666714.333333321.666666667】
当轴= 1 时数组的平均值: 17.6]
out _ arr:[0 1 2] arr 平均值,轴= 1: 【24 16 17】
摘要
在本教程中,我们介绍了numpy.mean()
,Numpy 库中的一个统计函数。我们介绍了什么是 mean,mean()函数的语法,mean()函数参数以及一些代码示例。