NumPy 的 std(~)
方法計算輸入數組中值的標準差。標準差使用以下公式計算:
其中,
-
是給定數組的大小(即樣本大小)
-
是 NumPy 數組中第 索引的值
-
是樣本平均值
注意
std(~)
方法還可以計算標準差的無偏估計。我們通過在參數中設置 ddof=1
來實現這一點,我們將在後麵的示例中看到。
參數
1. a
| array-like
輸入數組。
2. axis
| int
或 tuple
| optional
計算標準差所沿的軸。對於二維數組,允許的值如下:
軸 |
意義 |
---|---|
0 |
標準差將按列計算 |
1 |
標準差將按行計算 |
None |
標準差將在展平數組上計算 |
默認情況下,axis=None
。
3. dtype
| string
或 type
| optional
用於計算標準差的類型。如果輸入數組的類型為 int
,則將使用 float32
。如果輸入數組是其他數值類型,則將使用其類型。
4. ddof
| int
| optional
自由度δ。這可以用來修改前麵的分母:
默認情況下,ddof=0
。
返回值
int
表示所提供值的標準偏差。
例子
一維數組的標準差
np.std([1,2,3,4])
1.118
計算樣本標準差
要計算樣本標準差,請設置 ddof=1
:
np.std([1,2,3,4], ddof=1)
1.290
計算總體標準差
要計算總體標準差,請省略 ddof
參數或顯式設置 ddof=0
:
np.std([1,2,3,4]) # By default, ddof=0
1.118
二維數組的標準差
整個數組
如果不指定 axis 參數,NumPy 隻會將 NumPy 數組視為展平數組。
np.std([[1,2],[3,4]])
1.118
此代碼與 np.std([1,2,3,4])
基本相同。
按列
要按列計算標準差,請在參數中指定axis=0
:
np.std([[1,4],[2,6], [3,8]], axis=0)
array([0.81649658, 1.63299316])
在這裏,我們計算 [1,2,3]
(即第一列)和 [4,6,8]
(即第二列)的標準差。
逐行
要按列計算標準差,請在參數中指定axis=1
:
np.std([[1,4],[2,6], [3,8]], axis=1)
array([1.5, 2. , 2.5])
在這裏,我們計算三個標準差:第一行(即 [1,4]
)、第二行(即 [2,6]
)和第三行(即 [3,8]
)。
警告
有時數字類型 float32
可能不夠準確,無法滿足您的需求。如果您的應用程序需要更準確的數字,請在參數中設置dtype=np.float64
。這將占用更多內存,但會提供更準確的結果。
相關用法
- Python - statistics stdev()用法及代碼示例
- Python str.isidentifier用法及代碼示例
- Python Streamlit st.experimental_singleton.clear用法及代碼示例
- Python Scipy stats.cumfreq()用法及代碼示例
- Python Scipy stats.nanmean()用法及代碼示例
- Python NumPy startswith方法用法及代碼示例
- Python str.expandtabs用法及代碼示例
- Python Scipy stats.gengamma()用法及代碼示例
- Python Scipy stats.dweibull()用法及代碼示例
- Python Streamlit st.bokeh_chart用法及代碼示例
- Python Streamlit st.caption用法及代碼示例
- Python Streamlit st.text_input用法及代碼示例
- Python scipy stats.expon()用法及代碼示例
- Python Streamlit st.area_chart用法及代碼示例
- Python Streamlit st.title用法及代碼示例
- Python str.title用法及代碼示例
- Python Streamlit st.cache用法及代碼示例
- Python statistics.median_grouped用法及代碼示例
- Python Scipy stats.f()用法及代碼示例
- Python Streamlit st.experimental_singleton用法及代碼示例
- Python Streamlit st.empty用法及代碼示例
- Python Streamlit st.error用法及代碼示例
- Python Scipy stats.genexpon()用法及代碼示例
- Python Streamlit st.video用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 NumPy | std method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。