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