[英]Python: how to slice a csv file with respect to a column other than the first?
[英]How to compare first element of a column with other elements in CSV file in Python?
我想將一列的第一個元素與同一列和下一列的其他元素以及打印元素進行比較,該元素僅在兩個列中都存在一次,並且在其對應列中也存在一次值。 例如:
Col1 Col2
111243
111145
213111
289200
222213
在此示例中,243僅出現一次,而111(對應列中的值)則出現一次以上。 我只想打印
289200
我的代碼是:
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]
它給我每一列的唯一值
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
這將顯示:
289 200
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.