我是Python的初学者,我试图检查不同行中的两个值何时相同,如果它们相同,我想将该值添加到两行中的上一列中。例如,如果这是我的数据:
'ola', 'b', '', '', 'c323'
'hello', 'i', '', '', 'c324'
'hi', 'i', '', '', 'c324'
我希望它返回此值:
'ola', 'b', '', '', 'c323'
'hello', 'i', '', 'c324', 'c324'
'hi', 'i', '', 'c324', 'c324'
我尝试了几件事,例如这个:
with open(filename, "r+") as file_one:
reader_one = csv.reader(file_one, delimiter='\t')
with open(filename, "r+") as file_two:
reader_two = csv.reader(file_two, delimiter='\t')
for row in reader_one:
corresp_info = row[3]
xml_info = row[4]
for compare_row in reader_two:
xml_compare = compare_row[4]
if xml_info == xml_compare:
corresp_info = xml_info
else:
continue
答案 0 :(得分:0)
这是我的看法:
myCsv = open(filename, "r+").read().splitlines() #Opens the file and split it by lines
newCsv = [myCsv[0].split(',')] #Adding first line to new CSV
for i in range(1, len(myCsv)): #looping through lines disregarding the first
splitted = myCsv[i].split(',') #split it by commas
newCsv.append(splitted) #append it
for index, j in enumerate(splitted): #looping through comma separated values
if j == newCsv[i-1][index]: #testing if equal to value of last row
newCsv[i-1][index-1] = newCsv[i-1][index] #changing values
newCsv[i][index-1] = newCsv[i][index]
newCsv = map(lambda x: ','.join(x), newCsv) #remapping it into a csv like string
open('newFile', 'w').write('\n'.join(newCsv)) #putting it into a new file
请注意,这仅是我如何查看它的一个示例,因此它可能有错别字或错误(即使我尝试不做一些,但我不是在这里为您编写代码,所以我已经未经测试或调试)。由您自己制作代码