Python Numpy.std() - 标准差函数
Sohaib Atiq
2023年1月30日
NumPy
numpy.std() 函数计算给定数组沿指定轴线的标准差。
numpy.std() 语法
numpy.std(arr, axis=None, dtype=float64)
参数
arr |
数组类型 输入数组来计算标准差 |
axis |
None, int 或元素为 int 的元组 计算标准差的轴。 axis=0 表示沿列计算标准差,axis=1 表示沿行计算标准差。如果没有给定 axis,它将多维数组视为一个扁平化的列表。 |
dtype 是指沿行的标准差 |
dtype 或 None在计算标准差时使用的数据类型 |
返回值
它返回给定数组的标准差,或一个沿指定轴的标准差的数组。
示例代码:numpy.std() 与 1-D 数组
当 Python 一维数组是输入时,Numpy.std() 函数计算数组中所有值的标准差。
import numpy as np
arr = [10, 20, 30]
print("1-D array :", arr)
print("Standard Deviation of arr is ", np.std(arr))
输出:
1-D array : [10, 20, 30]
Standard deviation of arr is 8.16496580927726
这里,1-D 数组的元素为 10、20 和 30;因此,返回的 DataFrame 中的值是标准差,没有分配任何轴信息。
示例代码:numpy.std() 与 2-D 数组
import numpy as np
arr = [[10, 20, 30], [3, 50, 5], [70, 80, 90], [100, 110, 120]]
print("Two Dimension array :", arr)
print("SD of with no axis :", np.std(arr))
print("SD of with axis along column :", np.std(arr, axis=0))
print("SD of with axis aong row :", np.std(arr, axis=1))
输出:
Two Dimension array : [[10, 20, 30], [3, 50, 5], [70, 80, 90], [100, 110, 120]]
SD of with no axis : 41.21960159384798
SD of with axis along column : [40.73312534 33.54101966 45.87687326]
SD of with axis aong row : [ 8.16496581 21.6999744 8.16496581 8.16496581]
np.std(arr) 将输入数组视为扁平化数组,并计算这个一维扁平化数组的标准差。
np.std(arr, axis=0) 计算沿列的标准差。它返回 [40.73312534 33.54101966 45.87687326] 作为输入数组中每个列的标准差。
np.std(arr, axis=1) 计算沿行的标准差。它返回 [ 8.16496581 21.6999744 8.16496581 8.16496581] 作为输入数组中每行的标准差。
示例代码:numpy.std() 指定 dtype
import numpy as np
arr = [10, 20, 30]
print("Single Dimension array :", arr)
print("SD of Single Dimension array :", np.std(arr))
print("SD value with float32 data :", np.std(arr, dtype=np.float32))
print("SD value with float64 data :", np.std(arr, dtype=np.float64))
输出:
Single Dimension array : [10, 20, 30]
SD of Single Dimension array : 8.16496580927726
SD value with float32 data : 8.164966
SD value with float64 data : 8.16496580927726
如果在 numpy.std() 函数中给出 dtype 参数,则在计算标准差时使用指定的数据类型。
很明显,如果我们将 dtype 赋值为 float32 而不是 float64,标准差的分辨率就会降低。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe