计算给定 NumPy 数组的均值、标准差和方差
在 NumPy 中,我们可以通过两种方法计算给定数组沿第二个轴的均值、标准差和方差,第一种是使用内置函数,第二种是通过均值、标准差和方差的公式。
方法 1:使用numpy.mean() 、 numpy.std() 、 numpy.var()
Python
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)
Python3
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)
Python
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 5 6 7 8 9]
Mean: 4.5
std: 2.8722813232690143
variance: 8.25
方法 2:使用公式
Python3
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
示例:比较内置方法和公式
Python
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