Python Remove duplicates from csv if value in column duplicated

Viewed 74

I am trying to write csv parser so if i have the same name in the name column i will delete the second name's line. For example:

['CSE_MAIN\\LC-CSEWS61', 'DEREGISTERED', '2018-04-18-192446'],
['CSE_MAIN\\IT-Laptop12', 'DEREGISTERED', '2018-03-28-144236'],
['CSE_MAIN\\LC-CSEWS61', 'DEREGISTERED', '2018-03-28-144236']]

I need that the last line will be deleted because it has the same name as the first one.

What i wrote is:

file2 = str(sys.argv[2])
print ("The first file is:" + file2)
reader2 = csv.reader (open(file2))
with open("result2.csv",'wb') as result2:
    wtr2= csv.writer( result2 )
    for r in reader2:
        wtr2.writerow( (r[0], r[6], r[9] ))
newreader2 = csv.reader (open("result2.csv"))
sortedlist2 = sorted(newreader2, key=lambda col: col[2] , reverse = True)
for i in range(len(sortedlist2)):
    for j in range(len(sortedlist2)-1):
        if (sortedlist2[i][0] == sortedlist2[j+1][0] and sortedlist2[i][1]!=sortedlist2[j+1][1]):
            if(sortedlist2[i][1]>sortedlist2[j+1][1]):
                del sortedlist2[i][0-2]
            else:
                del sortedlist2[j+1][0-2]

Thanks.

1 Answers

Try with pandas:

import pandas as pd
df = pd.read_csv('path/name_file.csv')
df = df.drop_duplicates([0]) #0 this is columns which will compare.
df.to_csv('New_file.csv') #save to csv

This method delete all duplicates from columns 1.

If you need simple delete you can use method drop.

#You file after use pandas (print(df)):
            0                    1                 2
0   CSE_MAIN\LC-CSEWS61     DEREGISTERED    2018-04-18-192446
1   CSE_MAIN\IT-Laptop12    DEREGISTERED    2018-03-28-144236
2   CSE_MAIN\LC-CSEWS61     DEREGISTERED    2018-03-28-144236

For example you need delete 2 row.

df.drop(2,axis=0, inplace=True) #axis=0 means row, if you switch 1 this is columns. 

Output:

              0                  1                 2
0   CSE_MAIN\LC-CSEWS61     DEREGISTERED    2018-04-18-192446
1   CSE_MAIN\IT-Laptop12    DEREGISTERED    2018-03-28-144236
Related