[英]How to compare first element of a column with other elements in CSV file in Python?
I want to compare first element of a column with other elements of same column and next column and print element which is present once only in both the columns as well as value in its corresponding column. 我想将一列的第一个元素与同一列和下一列的其他元素以及打印元素进行比较,该元素仅在两个列中都存在一次,并且在其对应列中也存在一次值。 For eg: 例如:
Col1 Col2 Col1 Col2
111 243 111243
111 145 111145
213 111 213111
289 200 289200
222 213 222213
In this example 243 is present only once but 111(value in corresponding column) is present more then once. 在此示例中,243仅出现一次,而111(对应列中的值)则出现一次以上。 I want to print only 我只想打印
289 200 289200
My code is: 我的代码是:
import csv
from collections import Counter, OrderedDict
class OrderedCounter(Counter, OrderedDict):
pass
f = open("1.csv", 'r')
reader = csv.reader(f)
a = []
b = []
c = []
for row in reader:
a.append(row[0])
b.append(row[1])
val = [i for i,j in OrderedCounter(a).items() if j==1]
val1 = [i for i,j in OrderedCounter(b).items() if j==1]
It is giving me the unique values of each column 它给我每一列的唯一值
from collections import Counter
import csv
values = Counter()
data = {}
with open('1.csv') as f_input:
csv_input = csv.reader(f_input)
header = next(csv_input) # comment out if no actual header
for row in csv_input:
values[row[0]] += 1
values[row[1]] += 1
data[row[0]] = row[1]
for value, count in values.items():
try:
if count == 1 and values[data[value]] == 1:
print '{} {}'.format(value, data[value])
except KeyError as e:
pass
This would display: 这将显示:
289 200
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.