我有一个像这样的csv文件:
column1 column2
john kerry
adam stephenson
ashley hudson
john kerry
etc..
我想从此文件中删除重复项,仅获取:
column1 column2
john kerry
adam stephenson
ashley hudson
我写了这个脚本,删除了基于姓氏的重复项,但我需要删除基于姓氏和名字的重复项。
import csv
reader=csv.reader(open('myfilewithduplicates.csv', 'r'), delimiter=',')
writer=csv.writer(open('myfilewithoutduplicates.csv', 'w'), delimiter=',')
lastnames = set()
for row in reader:
if row[1] not in lastnames:
writer.writerow(row)
lastnames.add( row[1] )
答案 0 :(得分:20)
你真的很亲密。将这些列用作设置条目
entries = set()
for row in reader:
key = (row[0], row[1]) # instead of just the last name
if key not in entries:
writer.writerow(row)
entries.add(key)
答案 1 :(得分:11)
您现在可以在pandas中使用.drop_duplicates方法。我会做以下事情:
import pandas as pd
toclean = pd.read_csv('myfilewithduplicates.csv')
deduped = toclean.drop_duplicates([col1,col2])
deduped.to_csv('myfilewithoutduplicates.csv')
答案 2 :(得分:1)
快速的方法是使用以下技术创建一组唯一的行(从this帖子中的@CedricJulien采用)。您失去了在每行中存储列名称的DictWriter
好处,但它适用于您的情况:
>>> import csv
>>> with open('testcsv1.csv', 'r') as f:
... reader = csv.reader(f)
... uniq = [list(tup) for tup in set([tuple(row) for row in reader])]
...
>>> with open('nodupes.csv', 'w') as f:
... writer=csv.writer(f)
... for row in uniq:
... writer.writerow(row)
这使用@CedricJulien使用的相同技术,这是一个很好的单行删除重复行(定义为相同的名和姓)。这使用DictReader
/ DictWriter
类:
>>> import csv
>>> with open('testcsv1.csv', 'r') as f:
... reader = csv.DictReader(f)
... rows = [row for row in reader]
...
>>> uniq = [dict(tup) for tup in set(tuple(person.items()) for person in rows)]
>>> with open('nodupes.csv', 'w') as f:
... headers = ['column1', 'column2']
... writer = csv.DictWriter(f, fieldnames=headers)
... writer.writerow(dict((h, h) for h in headers))
... for row in uniq:
... writer.writerow(row)
...