从CSV行复制值并添加到ID为sam的行

2024-04-27 02:17:40 发布

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

我有一个CSV的邮政编码链接到一个ID。有多个不同的邮政编码归属于同一个ID在不同的行。我的输入如下:

ID      Postal Code  
1001    MK18 1TN
1001    MK18 1TL
1002    HP17 6DG
1002    HP17 6DH

我要做的是为每个唯一的ID创建一行,并列出该ID可用的所有相关邮政编码

我追求的输出类似于:

ID    Postal Codes
1001  MK18 1TN, MK18 1TL
1002  HP17 6DG, HP17 6DH

有人建议我如何用Python或SQL实现这一点吗?你知道吗


Tags: csvidsql链接code建议codes邮政编码
2条回答

python示例可能是:

#ID      Postal Code  
data = [
    ('1001', 'MK18 1TN'),
    ('1001', 'MK18 1TL'),
    ('1002', 'HP17 6DG'),
    ('1002', 'HP17 6DH'),
    ]
d = dict()
for id,pc in data:
    if id not in d:
        d[id] = []
    d[id].append(pc)
idkeys = d.keys()
idkeys.sort()
for k in idkeys:
    print k, ', '.join(d[k])

Python中有许多方法,例如使用csv模块读取输入(假设tab是delimter),并使用itertools.groupby()collections.defaultdict(list)对其进行分组。这里是groupby()。你知道吗

import csv
from itertools import groupby

with open('postcodes.csv') as infile, open('result.csv', 'w') as outfile:
    reader = csv.reader(infile, delimiter='\t')
    writer = csv.writer(outfile, delimiter='\t')
    writer.writerow(next(reader))     # copies the column headers into the output CSV
    for _id, postcodes in groupby(reader, lambda row: row[0]):
        writer.writerow([_id, ', '.join(postcode[1] for postcode in postcodes)])

相关问题 更多 >