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

标签 python excel count frequency

我希望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 %

最佳答案

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

然后通过去掉百分号来测试百分比是否大于 0,然后使用 if float(row[0].strip('%')) > 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

然后您可以根据 totalCountnumberOfPositives 计算所需的总和和百分比:

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

关于Python Excel 负数和正数出现的次数(计数/频率),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29191444/

相关文章:

python - 取两个日期时间值或列的中值

python - 测试一个 numpy 数组是否位于数组 a 和 b 之间

MySQL COUNT NULL 内容按列,GROUP 按列

php - 如何从多个 MySQL 数据库中添加值

excel - 使用单元格引用导出 XLS 文件

linux - 如何统计某个目录下所有文件中某个单词的出现次数?但每个文件每个单词的计数仅增加一次

python - 在 Python 中使用变量对列表进行切片

python - SQL 查询中无法识别的变量(从 CLI 参数分配)

excel - VBA-Excel 如何清除 ComboBox 项目

PHP - 从不同的文件格式 Word/Excel/Powerpoint/PDF/RTF 中提取文本