计算一个给定的NumPy数组的平均数、标准差和方差
在NumPy中,我们可以通过两种方法计算给定数组沿第二轴的平均数、标准差和方差,第一种是使用内置函数,第二种是通过平均数、标准差和方差的公式。
方法1:使用 numpy.mean() , numpy.std() **, **numpy.var()
import numpy as np
# Original array
array = np.arange(10)
print(array)
r1 = np.mean(array)
print("\nMean: ", r1)
r2 = np.std(array)
print("\nstd: ", r2)
r3 = np.var(array)
print("\nvariance: ", r3)
输出:
[0 1 2 3 4 5 6 7 8 9]
Mean: 4.5
std: 2.8722813232690143
variance: 8.25
方法2:
import numpy as np
# Original array
array = np.arange(10)
print(array)
r1 = np.average(array)
print("\nMean: ", r1)
r2 = np.sqrt(np.mean((array - np.mean(array)) ** 2))
print("\nstd: ", r2)
r3 = np.mean((array - np.mean(array)) ** 2)
print("\nvariance: ", r3)
输出:
[0 1 2 3 4 5 6 7 8 9]
Mean: 4.5
std: 2.8722813232690143
variance: 8.25
例子:比较内置的方法和公式。
import numpy as np
# Original array
x = np.arange(5)
print(x)
r11 = np.mean(x)
r12 = np.average(x)
print("\nMean: ", r11, r12)
r21 = np.std(x)
r22 = np.sqrt(np.mean((x - np.mean(x)) ** 2))
print("\nstd: ", r21, r22)
r31 = np.var(x)
r32 = np.mean((x - np.mean(x)) ** 2)
print("\nvariance: ", r31, r32)
输出:
[0 1 2 3 4]
Mean: 2.0 2.0
std: 1.4142135623730951 1.4142135623730951
variance: 2.0 2.0