numpy.mean() in Python

本文介绍了如何使用Python的numpy库来计算一维和二维数组的平均值。详细展示了通过设置不同的axis参数,可以沿行或列计算平均值,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

numpy.mean(arr, axis = None)

Compute the arithmetic mean (average) of the given data (array elements) along the specified axis.
即计算指定数据(数组元素)沿指定轴的算术平均值(平均值)

arr : [array_like]input array.
axis : [int or tuples of int]axis along which we want to calculate the arithmetic mean. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.
(axis = 0表示沿列,axis = 1表示沿行)

Code #1:

# 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

Code #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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值