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


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


numpy.nanmean()函數可用於計算忽略NaN值的數組平均值。如果數組具有NaN值,我們可以找出不受NaN值影響的均值。

 用法: numpy.nanmean(a, axis=None, dtype=None, out=None, keepdims=))

參數:
a:[arr_like]輸入數組
axis:我們可以使用axis = 1表示行方向或axis = 0表示列方向。
out:輸出數組
dtype:數組的數據類型
overwrite_input:如果為True,則允許使用輸入數組a的內存進行計算。輸入數組將通過調用中位數進行修改。
keepdims:如果將其設置為True,則縮小的軸將保留為尺寸1的尺寸。使用此選項,結果將相對於原始a正確廣播。


返回:返回數組元素的平均值

範例1:

# Python code to demonstrate the  
# use of numpy.nanmean  
import numpy as np  
    
# create 2d array with nan value.  
arr = np.array([[20, 15, 37], [47, 13, np.nan]])  
    
print("Shape of array is", arr.shape)  
    
print("Mean of array without using nanmean function:",  
                                           np.mean(arr))  
    
print("Using nanmean function:", np.nanmean(arr)) 
輸出:
Shape of array is (2, 3)
Mean of array without using nanmean function:nan
Using nanmean function:26.4

範例2:

# Python code to demonstrate the  
# use of numpy.nanmean  
# with axis = 0  
import numpy as np  
    
# create 2d matrix with nan value  
arr = np.array([[32, 20, 24],  
                [47, 63, np.nan],    
                [17, 28, np.nan], 
                [10, 8, 9]])  
    
print("Shape of array is", arr.shape)  
    
print("Mean of array with axis = 0:",  
             np.mean(arr, axis = 0))  
    
print("Using nanmedian function:",  
      np.nanmean(arr, axis = 0)) 
輸出:
Shape of array is (4, 3)
Mean of array with axis = 0:[ 26.5   29.75    nan]
Using nanmedian function:[ 26.5   29.75  16.5 ]

範例3:

# Python code to demonstrate the  
# use of numpy.nanmedian  
# with axis = 1  
import numpy as np  
    
# create 2d matrix with nan value  
arr = np.array([[32, 20, 24],  
                [47, 63, np.nan],    
                [17, 28, np.nan], 
                [10, 8, 9]])  
    
print("Shape of array is", arr.shape)  
    
print("Mean of array with axis = 1:",  
             np.mean(arr, axis = 1))  
    
print("Using nanmedian function:",  
      np.nanmean(arr, axis = 1)) 
輸出:
Shape of array is (4, 3)
Mean of array with axis = 1:[ 25.33333333          nan          nan   9.        ]
Using nanmedian function:[ 25.33333333  55.          22.5          9.        ]


相關用法


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