【问题标题】:Python Excel number of times a negative and positive number appears (count/frequency)Python Excel 出现负数和正数的次数(计数/频率)
【发布时间】:2015-05-25 07:59:32
【问题描述】:

我希望 python 计算一个负数和正数以二进制形式出现的次数 [1 个正数和 0 个负数]。此外,我希望 Python 计算总数中存在多少正数的百分比。在使用 Python Excel 时,我很难弄清楚这一点。

这是我现在拥有的代码:

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

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

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

我想得到的是这样的:

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 %

【问题讨论】:

标签: python excel count frequency


【解决方案1】:

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

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

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

然后你可以从totalCount和numberOfPositives计算出你需要的总和和百分比:

print 'Total Count =', totalCount
print 'Percentage of Positive numbers =', numberOfPositives * 100./totalCount, '%'

【讨论】:

  • 我试过了,还是不行。当我运行代码时,没有任何反应。此外,我认为您写的最后一部分 print 'Percentage of Positive numbers =', numOfPositives * 100./totalCount, '%' 应该改为 numberOfPostivies 吧???
  • 我以两种方式更正了我的答案:首先,解析示例文件中的百分比,其次,修复您指出的打字错误。对此感到抱歉。
  • 非常感谢。这已经让我紧张了一个星期了。再次感谢你:)
  • 没问题,希望你能看一下,学习概念,以便下次自己应用。概念比实现更强大。 :)
  • True :) 我仍然对循环不太满意。但这有助于我现在更好地理解它,再次感谢您:)
猜你喜欢
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多