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

2024-06-01 08:30:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有14列(A-N)在一个CSV文件我要找多少病人(总共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

Tags: 文件csvinimportipforifis
1条回答
网友
1楼 · 发布于 2024-06-01 08:30:36

这样就可以了

#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))

相关问题 更多 >