handle duplicate values separately in python
handle duplicate values separately in python
I have a csv file which contains rows like below:
113,25CNFW,"test1",1ALNAU,25CNFW
113,25D5L2,"test2",1ALNAU,25D5L2
114,MCF82H,"test3",307531,MCF82H
Now, I'm trying to extract 2nd and 4th column of every row by searching certain nos in the 1st column, but whenever the 1st column contains duplicates, my script logic fails as it treats duplicates as single entry. Is there any way to iterate over duplicates in python such that each duplicate value is considered as individual?
import csv
mycsv = "/home/test.csv"
def csv_read(fobj, mid):
reader = csv.reader(fobj)
for row in reader:
if mid in row:
contid = row[1]
accid = row[3]
return accid,contid
list = ['113','114']
for mid in list:
with open(mycsv,"r") as fobj:
detail = csv_read(fobj,mid)
print detail[0] + "," + detail[1]
Output:
1ALNAU,25CNFW
307531,MCF82H
Process finished with exit code 0
So, in short I want 113 to be considered twice.
I've tried working around with different options, but they didn't work :(
return
f.close()
with
Hi @blazetopher. Thanks for looking into my issue and the tips. The reason I'm using 'return' is because I'm passing values of 'accid' and 'contid' to further part of my code in my script. I've edited the original code now along with the output what I'm getting. I think if this isn't working, I may have to look into pandas library as you suggested.
– Optimus Prime
5 mins ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Hi @optimus-prime. I tried your code and it worked fine for me after removing the
returnstatement (since it's not a function). Also want to mention that you don't need thef.close()as thewithstatement provides code-control and closes the file for you automatically. You may also want to look at the pandas library which can be very helpful when working with tabular data.– blazetopher
yesterday