求列表中元素的均值

本文介绍了如何在Python中利用numpy库计算列表或矩阵的元素均值,详细讲解了mean函数的应用,包括不同axis参数的含义,并给出了具体示例。

1、引入numpy库

方式:import numpy as np或from numpy import *

2、涉及到的相关函数

2.1 mean(matrix,axis=0)
其中 matrix为一个矩阵,axis为参数,其功能:求取均值

以mn矩阵举例:
axis 不设置值,对 m
n 个数求均值,返回一个实数
axis = 0:压缩行,对各列求均值,返回 1* n 矩阵
axis =1 :压缩列,对各行求均值,返回m*1矩阵

import numpy as np
num1 = np.array([[1,2,3],[2,3,4],[3,4,5],[4,5,6]])
num2 = np.mat(num1)
print(num2) 

average=np.mean(num2) # 对所有元素求均值
print('所有元素的平均值为:{}'.format(average))
  
average1=np.mean(num2,0) # 压缩行,对各列求均值
print('各列的平均值为:{}'.format(average1))

average2=np.mean(num2,1) # 压缩列,对各行求均值
print('各行的平均值为:{}'.format(average2))
>>>
[[1 2 3]
 [2 3 4]
 [3 4 5]
 [4 5 6]]
所有元素的平均值为:3.5
各列的平均值为:[[2.5 3.5 4.5]]
各行的平均值为:[[2.]
 [3.]
 [4.]
 [5.]]

2.2 mat()函数
可以将目标数据的类型转换为矩阵

import numpy as np
num1=np.array([[1,2,6],[2,3,4],[3,4,5],[4,5,6]])
num2=np.mat(num1)
print(num2)
>>>
[[1 2 6]
 [2 3 4]
 [3 4 5]
 [4 5 6]]

3、应用实例

import numpy as np
score1=[1,4,6,5]
score2=[3,5,7,9]
score1+=score2
print(score1)
score3=[]
average=np.mean(score1)
print('平均成绩是:{}'.format(average))
for i in score1:
  if i<average:
    score3.append(i)
    continue
print('低于平均成绩的有:{}'.format(score3))
>>>
[1, 4, 6, 5, 3, 5, 7, 9]
平均成绩是:5.0
平均成绩是:[1, 4, 3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值