从CSV文件中计算男性和女性的数量

时间:2015-07-29 16:25:23

标签: python csv

我想在CSV文件中计算男性和女性骑手的数量(编码为1或2),但我的代码似乎不起作用。这是我的代码:

Men = 0
Women = 0
import csv
with open('dec2week.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print(row['gender'])
        if 'gender' == 1:
            'gender'Men += 1
        esle:
            'gender'Women += 1

print "Count for Men: ", Men
print "Count for women: ", Women

2 个答案:

答案 0 :(得分:2)

使用Counter dict进行计数:

import csv
from collections import Counter
from itertools import chain
with open('dec2week.csv') as csvfile:
    next(csvfile)
    counts = Counter(chain.from_iterable(csv.reader(csvfile)))

然后使用密钥获取计数:

print("Total male = {}".format(counts["1"]))
print("Total female = {}".format(counts["2"]))

要使用特定列,请为每行编制索引或使用DictReader方法:

 counts = Counter(row["gender"] for row in csv.DictReader(csvfile))

使用for循环,您需要通过键访问并比较返回到" 1"的值:

with open('dec2week.csv') as csvfile:
    m,f = 0,0
    for row in csv.DictReader(csvfile):
        if row["gender"] == "1":
            m += 1
        else:
            f += 1


print("Total male = {}".format(m))
print("Total female = {}".format(f))

答案 1 :(得分:1)

我认为您的gender值位于row['gender'],在这种情况下,您几乎就在那里,您只需要在{{1}中比较此值 }语句并修复了其他一些小的语法问题:

if

如果这不起作用,请发布您的CSV数据示例,以便我可以测试并找出可行的内容。