如何过滤csv中的两列?

2024-09-27 22:26:25 发布

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

所以我有一个csv(https://ufile.io/y4nr9),用''分隔,包含了诸如'name'、'survive'、'sex'等列。我想找出没有存活下来的男性的百分比并打印统计数据。以下是我目前为止的代码:

import csv
reader = csv.reader(open('titanic-new_alphabetized.csv'), delimiter= ',')
filtered = filter(lambda p: 'male' == p[3], reader)
dict = []

input('press ENTER to exit')

Tags: csv代码namehttpsioimportopenreader
3条回答

还应该将文件作为变量打开,以便以后可以轻松地关闭它。在

或使用with ... as打开文件。在

您正在使用list语法创建词典。在

您应该使用dict={}

在Python3中,您可以过滤它们并计算统计信息:

import csv

total, survived = 0, 0

with open('titanic-new_alphabetized.csv',  newline='') as csvfile:
    for row in filter(lambda p: 'male'==p[3], csv.reader(csvfile, delimiter= ',')):
        total += 1
        if int(row[0]):
            survived += 1

print('total: {}, survived: {} ({:.2f}%)'.format(total, survived, 
                                                 survived/total * 100))

输出:

^{pr2}$

相关问题 更多 >

    热门问题