我正在用python编写一段代码,在这里我正在处理数组。我将数据从csv按行加载到我的数组中。数据看起来有点像这样:
aaa,bbb,ccc,ddd,eee,fff,ggg,hhh
111,222,333,444,555,666,777,888
abb,acc,add,ddd,vvv,bxc,nyc,hhh现在,在第一行和第三行中--尽管这些行不完全匹配--我感兴趣的列是第4列和第8列,也就是说,如果两行在这些列中有相同的数据,那么这些数据应该被视为重复条目,而我的数组应该只有第一行和第二行,而不应该有第三行。
result=[]
for file in input_file:
f=open(file,'r')
reader = csv.reader(f, quotechar='"')#read csv
for row in reader:
if row:
#do some operations on the elements of row
if(row[3] and row[7] not in result):#
result.append(row)#load result in array
else:
continue我希望结果数组是这样的
aaa,bbb,ccc,ddd,eee,fff,ggg,hhh
111,222,333,444,555,666,777,888而输出是
aaa,bbb,ccc,ddd,eee,fff,ggg,hhh
111,222,333,444,555,666,777,888
abb,acc,add,ddd,vvv,bxc,nyc,hhh发布于 2019-03-28 07:42:32
要检查dups的数据是一对值(第3列和第7列使用基于零的编号)。名为seen的集合经常用于此目的。其基本思想是:
seen = set()
for row in reader:
data = (row[3], row[7])
if data in set:
continue
set.add(data)
# process row发布于 2019-03-28 07:23:26
1:使用pands 2加载csv :只为感兴趣的第3列( user pd.drop_duplicates() )获取数据
参考链接duplicates/][1]
import pandas as pd
df = pd.read_csv("YOUR_FILE_NAME")
df.drop_duplicates(subset['first_intrested_column','second_intrested_column'],keep
=False, inplace=True)发布于 2019-03-28 08:31:48
代码的问题是对重复项的测试是不正确的。
这里有一个我认为正确的版本:
import csv
from io import StringIO
from pprint import pprint, pformat
input_file = ['''
aaa,bbb,ccc,ddd,eee,fff,ggg,hhh
111,222,333,444,555,666,777,888
abb,acc,add,ddd,vvv,bxc,nyc,hhh
''',]
result=[]
for file in input_file:
# f=open(file,'r')
f = StringIO(file)
reader = csv.reader(f, quotechar='"') # read csv
for row in reader:
if row and not any((row[3] == r[3] and row[7] == r[7]) for r in result):
result.append(row) # load result in array
pprint(result)输出:
[['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh'],
['111', '222', '333', '444', '555', '666', '777', '888']]https://stackoverflow.com/questions/55391927
复制相似问题