##############################################
######## python计算excel平均值和标准差 #######
##############################################
''':数据源格式
编号 时间 仪器1 仪器2 仪器3 仪器4 仪器5 仪器6 仪器7 仪器8 仪器9 仪器10 分组 均值 标准差
FKQXK-r-02-01 20200702 100 101 102 103 104 144 106 107 108 201 A组
FKQXK-r-02-02 20200702 100 105 102 103 104 105 106 107 108 202 A组
FKQXK-r-02-03 20200702 100 101 111 151 104 105 117 107 108 203 A组
'''
引入库
import xlwings as xw
import xlrd
import math
wb = xw.Book('伽玛数据处理.xls') #这样的话就不会频繁打开新的Excel
引用Excel工作表,单元格
引用工作表
sht = wb.sheets[0] #sht = wb.sheets[第一个sheet名]====伽玛原始记录
引用单元格
rng = sht.range('a1') #rng = sht['a1'] #rng = sht[0,0] 第一行的第一列即a1,相当于pandas的切片
定义函数
def mean(list): #定义平均值函数
sum=0
j=len(list)
for i in list:
sum = sum+ int(i)
return sum/j
def StdEv(list): #计算标准差函数,参数是列表和平均值
sum = 0.0
n = len(list) #计算列表长度
for i in list:
sum = sum + int(i)
list_aver=sum / n #先计算平均值
sum1 = 0.0
for j in range(n):
sum1 += (list[j] - list_aver) ** 2 #差的平方
res = math.sqrt(sum1/n) #求开方后就是标准差
return res
pass
上面定义函数
引用区域
rng = sht.range('c2:l2')
rng = sht['c']
n2=sht['n2']
list= sht.range('c2:l2').value
print(list)
print(mean(list))
sht.range('n2').value = mean(sht.range('c2:l2').value)
rng = sht.range('a2').expand('table')
nrows = rng.rows.count #获取总行数,不含标题
for i in range(2,nrows+2): #nrows+2是因为总行数不含标题,且最后一个不循环
sht.range('n{}'.format(i)).value = mean(sht.range('c{}:l{}'.format(i,i)).value) #计算均值列
sht.range('o{}'.format(i)).value = StdEv(sht.range('c{}:l{}'.format(i,i)).value) #计算标准差列
保存工作簿
wb.save('伽玛数据处理_RESULT.xls')
退出工作簿(可省略)
wb.close()
#######end###############