Python实现Excel统计函数
人气:0需求分析
根据原始数据,计算出累计和、回撤、连续正确、连续错误、连续正确值与连续错误值6项数据,其中原始数据大于等于0认定为正确,原始数据小于0为错误。明白了要求,那我们就开始撸代码吧~
解决步骤
import pandas as pd #创建一个计算数据的函数 def calculate(df): pass #读取原始数据,将索引列去除 df = pd.read_excel('需求0621.xlsx',index_col=0) #调用计算数据的函数 calculate(df)
先把整体思路写好,再去想办法计算每项数据
#计算累计和 lst1 = [] sum = 0 for i in range(df.shape[0]): if i == 0: lst1.append(df['N'][i]) sum += df['N'][i] else: sum += df['N'][i] lst1.append(sum) df['累计和'] = lst1
#计算回撤 lst2 = [] max = 0 for i in range(df.shape[0]): if i == 0: lst2.append(0) elif df['累计和'][i] > max: max = df['累计和'][i] lst2.append(0) elif df['累计和'][i] < max: lst2.append(df['累计和'][i]-max) elif df['累计和'][i] == max: lst2.append(0) df['回撤'] = lst2
#计算连续正确的个数 lst3 = [] correct = 0 for i in range(df.shape[0]): if df['N'][i] >= 0: correct += 1 lst3.append(correct) else: lst3.append(0) correct = 0 df['连续正确'] = lst3
#计算连续错误的个数 lst4 = [] mistake = 0 for i in range(df.shape[0]): if df['N'][i] < 0: mistake += 1 lst4.append(mistake) else: lst4.append(0) mistake = 0 df['连续错误'] = lst4
#计算连续正确值 lst5 = [] for i in range(df.shape[0]): lst5.append('') right = 0 for i in range(df.shape[0]): if df['连续正确'][i] != 0: right += df['N'][i] elif df['连续正确'][i] == 0 and right != 0: lst5[i-1] = right right = 0 df['连续正确值'] = lst5
#计算连续错误值 lst6 = [] for i in range(df.shape[0]): lst6.append('') wrong = 0 for i in range(df.shape[0]): if df['连续错误'][i] != 0: wrong += df['N'][i] elif df['连续错误'][i] == 0 and wrong != 0: lst6[i-1] = wrong wrong = 0 df['连续错误值'] = lst6
最后将dataframe保存到excel
df.to_excel('完成计算.xlsx') print('保持成功')
最终结果
技术总结
虽然已经完成了要求计算出了所有的数据,但在写代码过程中计算的步骤都是基于python基础语法实现的,对于pandas的使用还要只有通过大量的练习才能够熟练的掌握
加载全部内容