python - Loop through csv rows and check for a specific value -
hello got question regarding loops. situation got csv file check whether in column3 (row[2]) value "1" present. if not skip , loop again add value:
i = 1 maxuserid = 7255 result_liked = [] open('source/to/file/user_id%i.csv' %i,'r') fin: row in csv.reader(fin, delimiter='\t'): if int(row[2]) >= 1: result_liked.append(row) += 1 else: += 1 #more code
the thing need loop runs code , after run completed add value "1" i variable.
the goal of code run whole code , after done want add value 1 2 , run loop again, untill maxuserid of 7255 reached. how can loop 1 till 7255?
edit:
import csv maxuserid = 7255 result_liked = [] in range(maxuserid): open('source/to/file/user_id%i.csv' %(i+1),'r') fin: row in csv.reader(fin, delimiter='\t'): if int(row[2]) >= 1: result_liked.append(row) training_data = result_liked[:2] test_data = result_liked[2:] training_data_bookid = [el[1] el in training_data] test_data_bookid = [el[1] el in test_data] #training_data_bookid_int = map(int, training_data_bookid) #python2 training_data_bookid_int = list(map(int, training_data_bookid)) #python3 test_data_bookid_int = list(map(int, test_data_bookid)) #python3 books_list = [] j in range(0,2): open('source/to/file/output_new.csv', 'rt') f: reader = csv.reader(f, delimiter=',', quotechar='"') row in reader: get_book_id = training_data_bookid_int[j] if get_book_id == int(row[0]): books_list.append([row[2],row[1]]) b = sorted(books_list, reverse=true, key=lambda x:int(x[0])) c = [el[1] el in b] c_int = list(map(int, c)) check_training_vs_test = set(c_int) & set(test_data_bookid_int) open("result.txt", "a") text_file: text_file.write("userid: %i || liked: %s || test: %f" % (i, len(test_data), len(check_training_vs_test)))
try following code
maxuserid = 7255 result_liked = [] in range(maxuserid): # loop iterates through users files open('source/to/file/user_id%d.csv' % (i+1),'r') fin: row in csv.reader(fin, delimiter='\t'): if int(row[2]) >= 1: result_liked.append(row)
update
i think need like:
maxuserid = 7255 in range(maxuserid): result_liked = [] # form separate list each csv file open('source/to/file/user_id%i.csv' %(i+1),'r') fin: row in csv.reader(fin, delimiter='\t'): if int(row[2]) >= 1: result_liked.append(row) if len(result_liked) < 3: # if list few elements go next file continue training_data = result_liked[:2] test_data = result_liked[2:] ...
Comments
Post a Comment