[英]Merge list concating unique values as comma seperated retaining original order from csv
[英]Python merge list concating unique values as comma seperated
我正在嘗試使它起作用。
這是我的數據:
data.csv
id,fname,lname,education,gradyear,attributes
1,john,smith,mit,2003,qa
1,john,smith,harvard,207,admin
1,john,smith,ft,212,master
2,john,doe,htw,2000,dev
嘗試使用此代碼。 在Internet上找到了此代碼,還沒有完全理解。
from itertools import groupby
import csv
import pprint
t = csv.reader(open('data.csv'))
t = list(t)
def join_rows(rows):
def join_tuple(tup):
for x in tup:
if x:
return x
else:
return x
return [join_tuple(x) for x in zip(*rows)]
for name, rows in groupby(sorted(t), lambda x:x[0]):
print join_rows(rows)
但是,它不會將唯一值合並為逗號分隔。
輸出為:
['1', 'john', 'smith', 'ft', '212', 'master']
['2', 'john', 'doe', 'htw', '2000', 'dev']
['id', 'fname', 'lname', 'education', 'gradyear', 'attributes']
我如何使它像:
['1', 'john', 'smith', 'mit,harvard,ft', '2003,207,212', 'qa,admin,master']
['2', 'john', 'doe', 'htw', '2000', 'dev']
['id', 'fname', 'lname', 'education', 'gradyear', 'attributes']
如果同一列有更多條目,則它也應該起作用。 不應限於3行。
Grrrrr ....有人有提示或想法嗎?
提前致謝!
您可以將join_rows
的定義join_rows
為
import itertools
def join_rows(rows):
return [(e[0] if i < 3 else ','.join(e)) for (i, e) in enumerate(zip(*rows))]
這是將屬於同一id的所有條目壓縮到元組中。 對於前三個元組,返回第一項; 對於后者,它們之間以逗號分隔。
['1', 'john', 'smith', 'ft,harvard,mit', '212,207,2003', 'master,admin,qa']
['2', 'john', 'doe', 'htw', '2000', 'dev']
['id', 'fname', 'lname', 'education', 'gradyear', 'attributes']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.