结果每三个为一个重复,选择其中两个差距小的平均
数据如下
"""
author: shuaijie
intro: 在三个测氮的值中选择两个相近的平均
date: 07/27/2020 11:28
"""
import pandas as pd
def main():
fp = pd.read_excel(r'C:\Users\admire\Desktop\测氮结果示例.xlsx') # 读取数据
result = []
identify = []
for i in range(int(len(fp)/3)):
std1 = (fp.iloc[i*3, 1] - fp.iloc[i*3+1, 1])**2
std2 = (fp.iloc[i*3, 1] - fp.iloc[i*3+2, 1])**2
std3 = (fp.iloc[i*3+2, 1] - fp.iloc[i*3+1, 1])**2 # 计算方差
if min(std1, std2, std3) == std1: # 选择方差小的两个值
result.append((fp.iloc[i*3, 1] + fp.iloc[i*3+1, 1])/2)
elif min(std1, std2, std3) == std2:
result.append((fp.iloc[i*3, 1] + fp.iloc[i*3+2, 1])/2)
else:
result.append((fp.iloc[i*3+2, 1] + fp.iloc[i*3+1, 1])/2)
identify.append(i)
identify.append(i)
identify.append(i) # 定义位置三个一组,计算原始方差和均值
fp.insert(0, 'ID', identify)
data_mean = fp.groupby(by='ID').mean()
data_std = fp.groupby(by='ID').std()
final_data = pd.merge(data_mean, data_std, on='ID', how='left')
final_data['最终值'] = pd.Series(result)
final = final_data[['值_x', '值_y', '最终值']] # 提取需要的值
final_2 = final.rename(columns={'值_x': '平均', '值_y': '方差'}) # 改变列名
final_2.to_excel(r'C:\Users\admire\Desktop\测氮结果筛选.xlsx') # 输出结果
if __name__ == '__main__':
main()
部分结果