我遇到了csv文件的问题,我需要一些信息。以下是我需要做的事情:
我有一个像这样订购的CSV文件:
bla country bla bla value
Germany Y
Germany Y
Germany N
Denmark N
Denmark N
Denmark Y
现在我想用python做的每次Y值都在同一列中。所以最后我得到了像德国这样的东西:2丹麦:1。
但是,我只能使用以下代码弄清楚如何计算列:
import csv
from collections import Counter, defaultdict
from itertools import imap
from operator import itemgetter
header_counter = defaultdict(Counter)
with open('airlines.csv') as input_file:
r = csv.reader(input_file, delimiter=',')
headers = next(r)
for row in r:
row_val = sum([w.isdigit() for w in row])
for header, val in zip(headers, row):
if not any(map(str.isdigit, val)):
header_counter[header].update({val: row_val})
for k, v in header_counter.iteritems():
print k, v
我认为上面的代码对任何人都有很大用处,因为它只计算每列的行数并过滤掉整数。我能得到的任何帮助都非常感谢,我仍然相当缺乏经验。
答案 0 :(得分:1)
这是你要找的吗?
import csv
from collections import Counter
data = '''country,value
Germany,Y
Germany,Y
Germany,N
Denmark,N
Denmark,N
Denmark,Y'''
r = csv.DictReader(data.split('\n'))
counter = Counter(
row.get('country')
for row in r
if row.get('value') == 'Y')
for k, v in counter.items():
print('{}: {}'.format(k, v))
答案 1 :(得分:0)
我认为@ smarx的答案是最美妙的方式。这是一个更冗长和实用的方法:
import csv
d = {}
with open('airlines.csv', 'r') as f:
# Sniff the CSV dialect
dialect = csv.Sniffer().sniff(f.read(1024))
# Move back to beginning of file
f.seek(0)
# DictReader uses the first row in the file as headers.
r = csv.DictReader(f, dialect=dialect)
# Plain iteration and counting in a normal dict.
for row in r:
# Plain incrementation of the "country" by one if "value" is
# 'Y'
if row['value'] == 'Y':
d[row['country']] = d.get(row['country'], 0) + 1
for k in d:
print('{} => {}'.format(k, d[k]))