當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Scipy stats.nanmean()用法及代碼示例


scipy.stats.nanmean(array, axis=0)函數通過忽略沿數組指定軸的數組元素的Nan(不是數字)值來計算算術平均值。

它的公式-

參數:
array :輸入具有包含Nan值的元素的數組或對象,以計算算術平均值。
axis : 要計算平均值的軸。默認情況下,軸= 0。


返回值:基於設置參數的數組元素的算術平均值(忽略Nan值)。

代碼1:

# Arithmetic Mean  
import scipy 
import numpy as np 
  
arr1 = [1, 3, np.nan, 27]  
   
print("Arithmetic Mean using nanmean :", scipy.nanmean(arr1)) 
  
print("Arithmetic Mean without handling nan value :", scipy.mean(arr1)) 

輸出:

Arithmetic Mean using nanmean : 10.333333333333334
Arithmetic Mean without handling nan value : nan

代碼2:使用多維數據

# Arithmetic Mean  
from scipy import mean 
from scipy import nanmean 
import numpy as np 
  
arr1 = [[1, 3, 27],  
        [3, np.nan, 6],  
        [np.nan, 6, 3],  
        [3, 6, np.nan]]  
   
print("Arithmetic Mean is :", mean(arr1))  
print("Arithmetic Mean handling nan :", nanmean(arr1))  
  
# using axis = 0 
print("\nArithmetic Mean is with default axis = 0 : \n",  
      mean(arr1, axis = 0)) 
print("\nArithmetic Mean handling nan with default axis = 0 : \n",  
      nanmean(arr1, axis = 0)) 
  
# using axis = 1 
print("\nArithmetic Mean is with default axis = 1 : \n",  
      mean(arr1, axis = 1))   
print("\nArithmetic Mean handling nan with default axis = 1 : \n",  
      nanmean(arr1, axis = 1))  

輸出:

Arithmetic Mean is : nan
Arithmetic Mean handling nan : 6.444444444444445

Arithmetic Mean is with default axis =0 : 
 [nan nan nan]

Arithmetic Mean handling nan with default axis =0 : 
 [ 2.33333333  5.         12.        ]

Arithmetic Mean is with default axis =1 : 
 [10.33333333         nan         nan         nan]

Arithmetic Mean handling nan with default axis =1 : 
 [10.33333333  4.5         4.5         4.5       ]


相關用法


注:本文由純淨天空篩選整理自vishal3096大神的英文原創作品 sciPy stats.nanmean() function | Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。