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


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

numpy.mean(arr,axis = None):計算沿指定軸的給定數據(數組元素)的算術平均值(平均值)。

參數:
arr :[數組]輸入數組。
axis :我們要沿其計算算術平均值的[int或int元組]。否則,它將考慮將arr展平(適用於所有
軸)。 axis = 0表示沿列,而axis = 1表示沿行。
out :[ndarray,可選]我們要在其中放置結果的不同數組。數組必須具有與預期輸出相同的尺寸。
dtype :[數據類型,可選]我們在計算均值時需要的類型。

結果:數組的算術平均值(如果軸不存在,則為標量值)或具有沿指定軸的平均值的數組的算術平均值。


代碼1:

# Python Program illustrating  
# numpy.mean() method  
import numpy as np 
    
# 1D array  
arr = [20, 2, 7, 1, 34] 
  
print("arr : ", arr)  
print("mean of arr : ", np.mean(arr)) 
   

輸出:

arr :  [20, 2, 7, 1, 34]
mean of arr :  12.8


代碼2:

# Python Program illustrating  
# numpy.mean() method    
import numpy as np 
    
  
# 2D array  
arr = [[14, 17, 12, 33, 44],   
       [15, 6, 27, 8, 19],  
       [23, 2, 54, 1, 4, ]]  
    
# mean of the flattened array  
print("\nmean of arr, axis = None : ", np.mean(arr))  
    
# mean along the axis = 0  
print("\nmean of arr, axis = 0 : ", np.mean(arr, axis = 0))  
   
# mean along the axis = 1  
print("\nmean of arr, axis = 1 : ", np.mean(arr, axis = 1)) 
  
out_arr = np.arange(3) 
print("\nout_arr : ", out_arr)  
print("mean of arr, axis = 1 : ",  
      np.mean(arr, axis = 1, out = out_arr))

輸出:

mean of arr, axis = None :  18.6

mean of arr, axis = 0 :  [17.33333333  8.33333333 31.         14.         22.33333333]

mean of arr, axis = 1 :  [24.  15.  16.8]

out_arr :  [0 1 2]
mean of arr, axis = 1 :  [24 15 16]


相關用法


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