【发布时间】:2015-03-29 18:17:53
【问题描述】:
当数字为正数时,我想找到平均数,当数字为负数时,我想找到平均数。
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 的新手,不知道在哪里或如何做。
更新
我想要这部分的 row[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
【问题讨论】:
-
您的要求有点不清楚。您想要所有正行 [0] 值的平均值和所有负行 [0] 值的平均值吗?
-
是的,汤姆