如何在列中拆分和查找0的数量

时间:2016-04-12 02:11:43

标签: python csv

我在CSV文件中有14列(AN)我希望找到有多少患者(总共303个)有0个心脏病征兆这将在第14栏(N)中,任何高于0的人都将被视为生病患者和0患者都是健康的。

到目前为止,我在代码中的内容是这样的。我知道我很可能做错了所以如果我犯了错误,请纠正我。

    import csv
import math
with open("train.csv", "r") as f:
#HP is healthy patient IP is ill patients
    for c in f.read():
        chars.append(c)
num_chars = len(chars)
num_IP = 0;
num_HP = 0;
for c in chars:
    if c > 0:
        num_IP += 1
    if c <=0:
        num_HP += 1

1 个答案:

答案 0 :(得分:1)

这应该这样做。

#turn csv files into a list of lists
with open('train.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=',')
     csv_data = list(reader)

#count the amount of patients with heart problems
count = 0
for row in csv_data:
    try:
        if (row and int(row[13]) > 0):
            count += 1
    except IndexError:
        print("could not find the heart diseases status for the row" + str(row))

print("the amount of patients with heart disease is " + str(count))