pythonexcelfind平均正数和平均负数

我需要一些帮助。 我想知道当数字是正数时平均数字是多less,当数字是负数时我想find平均数字。

import csv totalCount = 0 numberOfPositives = 0 with open('Weather30States.csv', 'r') as file1: val = list(csv.reader(file1))[2] val1 = val[0:4] with open('FL%.csv', 'r') as file2: reader = csv.reader(file2) reader.next() # this skips the first row of the file # this iteration will start from the second row of file2.csv conditionMet = False for row in reader: if conditionMet == True: if float(row[0].strip('%')) > 0: # change > to >= if you want to count 0 as positive print "FA, 1",row[0],',', ','.join(row[1:5]) # print 1 if positive numberOfPositives += 1 # add 1 to numberOfPositives only if positive else: print "FA, 0",row[0],',', ','.join(row[1:5]) # print 0 if not positive totalCount += 1 # add 1 to totalCount regardless of sign conditionMet = False # or break if you know you only need at most one line if row[1:5] == val1: conditionMet = True print 'Total Count =', totalCount print 'Percentage of Positive numbers =', numberOfPositives * 100./totalCount, '%' 

我对python和excel是如此的新颖,我不知道在哪里或如何去做。 谢谢

更新:

我想从这部分行[0]的平均值

 with open('FL%.csv', 'r') as file2: reader = csv.reader(file2) reader.next() # this skips the first row of the file # this iteration will start from the second row of file2.csv conditionMet = False for row in reader: if conditionMet == True: if float(row[0].strip('%')) > 0: # change > to >= if you want to count 0 as positive print "FA, 1",row[0],',', ','.join(row[1:5]) # print 1 if positive numberOfPositives += 1 # add 1 to numberOfPositives only if positive else: print "FA, 0",row[0],',', ','.join(row[1:5]) # print 0 if not positive totalCount += 1 # add 1 to totalCount regardless of sign conditionMet = False # or break if you know you only need at most one line if row[1:5] == val1: conditionMet = True 

你可以随时收集你的正面和负面的价值,然后平均他们在最后。

 from numpy import mean neg_vals,pos_vals = [],[] #Two empty lists to add values into #Your code goes here ... ... ... ... if float(row[0].strip('%')) > 0: # change > to >= if you want to count 0 as positive print "FA, 1",row[0],',', ','.join(row[1:5]) # print 1 if positive numberOfPositives += 1 # add 1 to numberOfPositives only if positive pos_vals.append(float(row[0])) else: print "FA, 0",row[0],',', ','.join(row[1:5]) # print 0 if not positive neg_vals.append(float(row[0])) #Rest of with open as file2 neg_mean = mean(neg_vals) pos_mean = mean(pos_vals) 

你可能不得不格式化行[0](看起来你通常会从中删除'%')。

这个代码的工作原理是在列表中添加正值和负值。 在循环结束时,您取两个列表的平均值。 根据你想要代码的灵活性,你可能需要包含一个没有正值或负值的testing用例。