pythonopencsvsift

How Iterate each element row and compare with another elements in row


I have to fetch the values from CSV within my local machine and iterate each element and compare them with each element of another row.

Comparison image

My CSV is stored in my Local C drive and read the value, now I need help to iterate each element from source and target.

import csv
with open('C:\\Users\\user\\Desktop\\test_readwrite.csv') as cs:
csv_reader = csv.reader(cs)
#displaying it line by line
for line in csv_reader:
    print(line)
#closing the connection
cs.close()

Solution

  • I am pretty sure this could be marked as a duplicate. Nevertheless, using pandas should make it easier to compare.

    import pandas as pd
    
    df = pd.read_csv('data.csv')
    
    # Compare column 1 and column 2
    def compare(x, y):
        # Your condition, return true or false
        # I am using equality
        return x == y
    
    df['result'] = df.apply(lambda x: compare(x['col1'], x['col2']), axis=1)
    

    This should about fulfil your requirement