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


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


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

參數:
array:具有元素(包括Nan值)的輸入數組或對象,以計算中位數。
axis:計算中值所沿的軸。默認情況下軸= 0

返回:基於設置參數的數組元素的中位數(忽略Nan值)。


代碼1:

# median  
import scipy 
import numpy as np 
  
arr1 = [1, 3, np.nan, 27, 2, 5]  
   
print("median using nanmedian:", scipy.nanmedian(arr1)) 
  
print("median without handling nan value:", scipy.median(arr1)) 

輸出:

median using nanmedian:3.0
median without handling nan value:nan


代碼2:多維數據

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

輸出:

median is:nan
median handling nan:3.0

median is with default axis = 0:
 [ nan  nan  nan]

median handling nan with default axis = 0:
 [ 3.  6.  6.]

median is with default axis = 1:
 [  3.  nan  nan  nan]

median handling nan with default axis = 1:
 [ 3.   4.5  4.5  4.5]


相關用法


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