首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python Excel出现负数和正数的次数(计数/频率)

Python Excel出现负数和正数的次数(计数/频率)
EN

Stack Overflow用户
提问于 2015-03-22 13:48:46
回答 1查看 237关注 0票数 1

我想让python计算负数和正数在二进制中出现的次数,1是正数,0是负数。此外,我希望Python计算总计数中存在的正数的百分比。在使用Python Excel时,我很难弄清楚这一点。

这是我现在拥有的代码:

代码语言:javascript
复制
import csv

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:
            print "FA,",row[0],',', ','.join(row[1:5])
            conditionMet = False # or break if you know you only need at most one line
        if row[1:5] == val1:
           conditionMet = True

当我运行这段代码时,我在输出窗口中得到的结果是:

代码语言:javascript
复制
FA, -1.97% , 0,0,1,0
FA, -0.07% , 0,0,1,1
FA, 0.45% , 0,1,1,1
FA, -0.07% , 0,0,1,1
FA, -0.28% , 0,0,1,1

我想得到的是:

代码语言:javascript
复制
1, 0, FA, -1.97% , 0,0,1,0
2, 0, FA, -0.07% , 0,0,1,1
3, 1, FA, 0.45% , 0,1,1,1
4, 0, FA, -0.07% , 0,0,1,1
5, 0, FA, -0.28% , 0,0,1,1

Total Count = 5
Percentage of Positive numbers = .20 %
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-22 15:03:57

使用两个计数器变量来跟踪总计数和阳性数。在开始时将它们设置为0,然后在循环内部,每当您想要添加1时,使用+= 1递增它们。

然后测试百分比是否大于0,方法是去掉百分号,然后使用if float(row[0].strip('%')) > 0将字符串转换为数字。如果您想在“积极”类别中包含0,您可以将其更改为>=

代码语言:javascript
复制
totalCount = 0
numberOfPositives = 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

然后,您可以从totalCountnumberOfPositives中计算所需的总和和百分比

代码语言:javascript
复制
print 'Total Count =', totalCount
print 'Percentage of Positive numbers =', numberOfPositives * 100./totalCount, '%'
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29191444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档